我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
当前回答
如果正则表达式包含一个变量,请确保转义它。
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
可以这样使用
new RegExp(escapeRegExp(searchString), 'i')
或者在mongoDb查询中
{ '$regex': escapeRegExp(searchString) }
在这里发表同样的评论
其他回答
这是完成这项任务最简单的方法
如果您希望查询区分大小写
db.getCollection("users").find({'username':/Son/})
如果您希望查询不区分大小写
db.getCollection("users").find({'username':/Son/i})
对于聚合框架
领域搜索
('$options': 'i'用于不区分大小写搜索)
db.users.aggregate([
{
$match: {
'email': { '$regex': '@gmail.com', '$options': 'i' }
}
}
]);
全文检索
(仅适用于文本索引的字段
db.articles.aggregate([
{
$match: { $text: { $search: 'brave new world' } }
}
])
由于这是在搜索引擎的第一个点击之一,上面没有一个似乎适用于MongoDB 3。X,这里有一个正则表达式搜索是有效的:
db.users.find( { 'name' : { '$regex' : yourvalue, '$options' : 'i' } } )
不需要创建额外的索引或类似的。
从2.4版开始,您可以在字段上创建一个文本索引来进行搜索,并使用$text操作符进行查询。
首先,创建索引:
db.users。createIndex({"username": "text"})
然后,搜索:
db.users。查找({$text: {$search: "son"}})
基准测试(~150K文档):
Regex(其他答案)=> 5.6-6.9秒 文本搜索=> .164-。201秒
注:
A collection can have only one text index. You can use a wildcard text index if you want to search any string field, like this: db.collection.createIndex( { "$**": "text" } ). A text index can be large. It contains one index entry for each unique post-stemmed word in each indexed field for each document inserted. A text index will take longer to build than a normal index. A text index does not store phrases or information about the proximity of words in the documents. As a result, phrase queries will run much more effectively when the entire collection fits in RAM.
如果正则表达式包含一个变量,请确保转义它。
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
可以这样使用
new RegExp(escapeRegExp(searchString), 'i')
或者在mongoDb查询中
{ '$regex': escapeRegExp(searchString) }
在这里发表同样的评论