0

I am working on a db query in mongo where i need to query the document by regular expressing the string field(fieldToQuery).

the datastructure is like

{
     fieldToQuery : "4052577300",
     someOtherField : "some value",
     ...
     ...
}

I have the value like "804052577300", using which i have to query the above document.

How to achieve the same using $regex operator?

Update:

I need to do like ends with regex in mongo.

2 Answers 2

2

You could do a sort of reverse regex query where you create a regex using the fieldToQuery value and then test that against your query value:

var value = "804052577300";        
db.test.find({
    $where: "new RegExp(this.fieldToQuery + '$').test('" + value + "');" 
});

The $where operator allows you to execute arbitrary JavaScript against each doc in your collection; where this is the current doc, and the truthy result of the expression determines whether the doc should be included in the result set.

So in this case, a new RegExp is built for each doc's fieldToQuery field with a $ at the end to anchor the search to the end of the string. The test method of the regex is then called to test whether the value string matches the regex.

The $where string is evaluated server-side, so value's value must be evaluated client-side by directly including its value into the $where string.

Note that $where queries can be quite slow as they can't use indexes.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your effort on this, will surely give it a try and will let you know. It'll be great if you could just give short explanation. update : beauty, worked like a charm.
until the 'new RegExp' i understood, I figured out that we can use the field directly by seeing your 'this.fieldToQuery', but after that is little confusing.
@Beast No problem, I added some more explanation; hope that helps.
1

You could do something like this:

db.collection.find({ fieldToQuery: /4052577300$/})

The regex pattern above is equivalent to the SQL's LIKE operation:

select * from table where fieldToQuery like '%4052577300' => will return the document with the value "804052577300"

1 Comment

the value i said will be dynamic sequence prefixed with the number in the fieldToQuery. so i may have "804052577300" or "8804052577300".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.