如何查找文档,哪个字段是特定字符串的子字符串? [英] How to find documents, which field is a substring to the specific string?
问题描述
有什么方法可以在MongoDB集合中找到文档,哪个字段是我的 string 的子字符串?
Is there any way to find a document in MongoDB collection, which field is a substring to my "string"?
只是小例子。假设我有这个集合:
Just a little example. Suppose I have this collection:
{"str": "pho", ...},
{"str": "sma", ...},
{"str": "goa", ...},
{"str": "aba", ...},
{"str": "gag", ...}
...
例如,我的字符串 是智能手机。因此查询的结果应为:
And my "string" is "smartphone" for example. So the result of the query should be:
{"str": "pho", ...}
{"str": "sma", ...}
现在我使用此正则表达式来解决我的问题:
For now I use this regex to solve my problem:
^[smartphone]+$
可以,但是也可以匹配 { str: ophms,...}
这样的文档 str不是 smartphone的子字符串。
That works, but it'll also match documents like {"str": "ophms", ...}
which "str" is not a substring of "smartphone".
我知道,我的问题与#2123738 ,但这与sql数据库有关,查询方法有所不同
I know, my question is exact like a #2123738, but that's about sql databases, which querying methods differents a lot.
推荐答案
您可以使用 $ indexOfCP
查找一个字符串是另一个的子字符串,如果是,它将返回起始索引,否则返回 -1
You can use $indexOfCP
to find a string is a substring of other, if yes it will return the starting index otherwise -1
{$expr : {$gte : [{$indexOfCP: ["smartphone","$str"]},0]}}
收藏
> db.t60.find()
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2de"), "str" : "pho" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2df"), "str" : "sma" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2e0"), "str" : "goa" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2e1"), "str" : "aba" }
结果
> db.t60.find({$expr : {$gte : [{$indexOfCP: ["smartphone","$str"]},0]}})
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2de"), "str" : "pho" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2df"), "str" : "sma" }
这篇关于如何查找文档,哪个字段是特定字符串的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!