我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
使用聚合子字符串搜索(带索引!!!):
db.collection.aggregate([{
$project : {
fieldExists : {
$indexOfBytes : ['$field', 'string']
}
}
}, {
$match : {
fieldExists : {
$gt : -1
}
}
}, {
$limit : 5
}
]);
其他回答
查找结果的一种方法相当于类似查询:
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
其中i用于不区分大小写的提取数据。
我们还可以通过另一种方式获得结果:
db.collection.find({"name":/aus/})
上面将提供名称中包含aus的结果。
您可以在MongoDB中使用正则表达式。
例如
db.users.find({"name": /^m/})
由于MongoDB外壳支持正则表达式,这是完全可能的。
db.users.findOne({"name" : /.*sometext.*/});
如果我们希望查询不区分大小写,可以使用“i”选项,如下所示:
db.users.findOne({"name" : /.*sometext.*/i});
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
有多种方法可以实现这一点。
最简单的一个:
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中找到。