我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
对于PHP mongo Like。
我对PHP mongo有几个问题。我发现串联正则表达式参数在某些情况下会有所帮助——PHP mongo find字段以开头。
例如
db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);
// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)
// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john, jason)
其他回答
使用JavaScript RegExp
按空格拆分名称字符串,并生成单词数组映射到迭代循环,并将字符串转换为名称中每个单词的正则表达式
let name=“My name”.split(“”).map(n=>新RegExp(n));console.log(名称);
结果:
[/My/, /Name/]
有两种情况可以匹配字符串,
$in:(类似于$or条件)
尝试在表达式中使用$。要在$in查询表达式中包含正则表达式,只能使用JavaScript正则表达式对象(即/patter/)。例如:
db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]
$all:(类似于$和条件)文档应包含所有单词
db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]
使用嵌套的$and和$or条件和$regex
有两种情况可以匹配字符串,
$或:(类似于$in条件)
db.users.find({
$or: [
{ name: { $regex: "My" } },
{ name: { $regex: "Name" } }
// if you have multiple fields for search then repeat same block
]
})
游戏场
$和:(类似于$all条件)文档应包含所有单词
db.users.find({
$and: [
{
$and: [
{ name: { $regex: "My" } },
{ name: { $regex: "Name" } }
]
}
// if you have multiple fields for search then repeat same block
]
})
游戏场
In
使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go
您可以执行以下操作:
db.users.find({'name': {'$regex': 'sometext'}})
MongoRegex已被弃用。
使用MongoDB \ BSON \ Regex:
$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
Use:
const indexSearch = await UserModel.find(
{ $text: { $search: filter } },
);
if (indexSearch.length) {
return indexSearch;
}
return UserModel.find(
{
$or: [
{ firstName: { $regex: `^${filter}`, $options: 'i' } },
{ lastName: { $regex: `^${filter}`, $options: 'i' } },
{ middleName: { $regex: `^${filter}`, $options: 'i' } },
{ email: { $regex: `^${filter}`, $options: 'i' } },
],
},
);
我使用了正则表达式和“索引”的组合。
有多种方法可以实现这一点。
最简单的一个:
db.users.find({"name": /m/})
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
db.users.find({ "name": { $regex: "m"} })
更多详细信息可以在$regex中找到。