我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
当前回答
https://docs.mongodb.com/manual/reference/sql-comparison/
http://php.net/manual/en/mongo.sqltomongo.php
MySQL
SELECT * FROM users WHERE username LIKE "%Son%"
MongoDB
db.users.find({username:/Son/})
其他回答
下面是通过Python连接MongoDB时必须做的事情
db.users.find({"username": {'$regex' : '.*' + 'Son' + '.*'}})
你也可以使用一个变量名来代替'Son',因此字符串连接。
您可以使用以下代码来实现。
db.users.findOne({"username" : {$regex : "son"}});
我使用这个代码,它的工作搜索子字符串
db.users.find({key: { $regex: new RegExp(value, 'i')}})
如果正则表达式包含一个变量,请确保转义它。
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
可以这样使用
new RegExp(escapeRegExp(searchString), 'i')
或者在mongoDb查询中
{ '$regex': escapeRegExp(searchString) }
在这里发表同样的评论
对于聚合框架
领域搜索
('$options': 'i'用于不区分大小写搜索)
db.users.aggregate([
{
$match: {
'email': { '$regex': '@gmail.com', '$options': 'i' }
}
}
]);
全文检索
(仅适用于文本索引的字段
db.articles.aggregate([
{
$match: { $text: { $search: 'brave new world' } }
}
])