mongodb 如何在Mongodb的字段中查找子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10242501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a substring in a field in Mongodb
提问by codious
How can I find all the objects in a database with where a field of a object contains a substring?
如何在对象的字段包含子字符串的情况下找到数据库中的所有对象?
If the field is A in an object of a collection with a string value:
如果该字段是具有字符串值的集合对象中的 A:
I want to find all the objects in the db "database" where A contains a substring say "abc def".
我想在 db“数据库”中找到所有对象,其中 A 包含一个子字符串,比如“abc def”。
I tried:
我试过:
db.database.find({A: {$regex: '/^*(abc def)*$/''}})
but didn't work
但没有用
UPDATE
更新
A real string (in unicode):
一个真正的字符串(unicode):
Sujet Commentaire sur Star Wars Episode III - La Revanche des Sith 1
Need to search for all entries with Star Wars
需要用星球大战搜索所有条目
db.test.find({A: {$regex: '^*(star wars)*$''}}) not wokring
回答by Derick
Instead of this:
取而代之的是:
db.database.find({A: {$regex: '/^*(abc def)*$/''}})
You should do this:
你应该做这个:
db.database.find({A: /abc def/i })
^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the character following" and (abc def)* means "0 or more times "abc def", but it has to be at the end of the string, because of your $. The "i" at the end is to make it case insensitive.
^* 实际上不是有效的语法,因为 ^ 和 $ 是锚点而不是可重复的东西。你可能是指 ^.* 在这里。但是不需要 ^.* 因为它只是表示“直到字符后面的所有内容”,而 (abc def)* 表示“0 次或多次“abc def”,但它必须位于字符串的末尾,因为你的 $. 最后的“i”是为了不区分大小写。
回答by LuisCarlos Rodriguez
回答by dev101
$regex
is too expensive/slow on large collections.
$regex
在大型集合上太昂贵/太慢。
I'd suggest to leverage aggregation framework and $indexOfCP.
我建议利用聚合框架和$indexOfCP。
db.test.aggregate([{$match:
{$expr: { $gt: [{ $indexOfCP: [ "$A", "Star Wars" ] }, -1]}}
}, {$project: {A:1}}])
For case-insensitive search you may add $toUpper
to the mix and search for STAR WARS
.
对于不区分大小写的搜索,您可以添加$toUpper
到组合中并搜索STAR WARS
.
回答by Alex Jolig
This worked for me:
这对我有用:
db.test.find({"A": {'$regex': '.*star wars.*'}})