我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
MongoRegex已被弃用。
使用MongoDB \ BSON \ Regex:
$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
其他回答
如果您使用的是Spring Data MongoDB,可以通过以下方式实现:
String tagName = "m";
Query query = new Query();
query.limit(10);
query.addCriteria(Criteria.where("tagName").regex(tagName));
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
以下是使用“从”范例的命令:
db.customer.find({"customer_name" : { $regex : /^startswith/ }})
db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})
因此:
For:
db.users.find({name: /a/}) // Like '%a%'
输出:patrick,petra
For:
db.users.find({name: /^pa/}) // Like 'pa%'
输出:patrick
For:
db.users.find({name: /ro$/}) // Like '%ro'
输出:pedro
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' } },
],
},
);
我使用了正则表达式和“索引”的组合。