MongoDB - find if field value is contained in a given string

Can I request documents that contain a specific field in a given line?

for example if I have these docs:

{a: 'test blabla'},
{a: 'test not'}

      

I would like to find all documents that the field is a

fully included in the string "test blabla test"

, so only the first document will be returned .

I know I can do this aggregation

with using $indexOfCP

, and also possibly with $where

and mapReduce

. I wandered if it is possible to do this in a query find

using MongoDB standard operators (e.g. $ gt, $ in).

thank.

+3


source to share


2 answers


I can think of two ways to do this:

Option 1

Using $ where :

db.someCol.find( { $where: function() { return "test blabla test".indexOf(this.a) > -1; } }

      

Explanation: Find all documents whose field value "a" is found in some given string.

This approach is versatile because you can run any code you like but is less recommended from a performance standpoint. For example, it cannot use indexes. Read completely $ where considerations here: https://docs.mongodb.com/manual/reference/operator/query/where/#considerations



Option 2

Using regular matches using regular expressions, ONLY under certain circumstances; Below is an example that only works with a match that the field value is found as the initial substring of the given string:

db.someCol.find( { a : /^(t(e(s(t( (b(l(a(b(l(a( (t(e(s(t)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?$/ } )

      

Clarification: Break up the components of your "should-be-contains-inside" string and match with all the additional features of this with a regex.

In your case, this option is very crazy, but it's worth noting that there might be specific cases (like a limited namespace match) where you wouldn't need to split every letter, but some very finite set of predefined parts. And in this case, this option can still use indices and not suffer from $ where performance pentalties (as long as the complexity of the regex does not outweigh this benefit :)

+1


source


You can use regular expression to search.



db.company.findOne({"companyname" : {$regex : ".*hello.*"}});

      

0


source







All Articles