我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。
喜欢的东西:
db.users.findOne({$contains:{"username":"son"}})
这可能吗?
当前回答
如果需要搜索多个属性,可以使用$or。例如
Symbol.find(
{
$or: [
{ 'symbol': { '$regex': input, '$options': 'i' } },
{ 'name': { '$regex': input, '$options': 'i' } }
]
}
).then((data) => {
console.log(data)
}).catch((err) => {
console.log(err)
})
在这里,您将根据输入是否包含在符号属性或名称属性中进行搜索。
其他回答
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/})
从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.
这样就可以了
db.users.find({ username: { $in: [ /son/i ] } });
i只是为了防止限制匹配单个字母的大小写。
您可以在MongoDB文档中查看$regex文档。 这里有一个链接:https://docs.mongodb.com/manual/reference/operator/query/regex/
下面是通过Python连接MongoDB时必须做的事情
db.users.find({"username": {'$regex' : '.*' + 'Son' + '.*'}})
你也可以使用一个变量名来代替'Son',因此字符串连接。
我使用这个代码,它的工作搜索子字符串
db.users.find({key: { $regex: new RegExp(value, 'i')}})