我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
查找结果的一种方法相当于类似查询:
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
其中i用于不区分大小写的提取数据。
我们还可以通过另一种方式获得结果:
db.collection.find({"name":/aus/})
上面将提供名称中包含aus的结果。
其他回答
将模板文字与变量一起使用也有效:
{“firstname”:{$regex:`^${req.body.firstname}.*`,$options:'si'}}
您有两个选择:
db.users.find({"name": /string/})
or
db.users.find({"name": {"$regex": "string", "$options": "i"}})
对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。
关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。
我找到了一个免费的工具来将MySQL查询转换为MongoDB:http://www.querymongo.com/
我检查了几个问题。在我看来,几乎所有这些都是正确的。据此,答案是
db.users.find({
"name": "%m%"
});
有多种方法可以实现这一点。
最简单的一个:
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中找到。
类似的查询如下所示:
db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);
对于Scala ReactiveMongo API,
val query = BSONDocument("title" -> BSONRegex(".*" + name + ".*", "")) // like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]