How to find documents, which field is a substring

2019-07-26 10:30发布

问题:

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]+$

That works, but it'll also match documents like {"str": "ophms", ...} which "str" is not a substring of "smartphone".

I know, my question is exact like a #2123738, but that's about sql databases, which querying methods differents a lot.

回答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]}}

collection

> db.t60.find()
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2de"), "str" : "pho" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2df"), "str" : "sma" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2e0"), "str" : "goa" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2e1"), "str" : "aba" }

result

> db.t60.find({$expr : {$gte : [{$indexOfCP: ["smartphone","$str"]},0]}})
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2de"), "str" : "pho" }
{ "_id" : ObjectId("5c44c5cc9d56bf65be5ab2df"), "str" : "sma" }