Search code examples
mongodbsql-likeregexp-like

Mongo DB find - SQL Like - wildcard in the middle


This question is very similar to How to query MongoDB with "like"?, yet I have not been able to use that or the documentation here https://docs.mongodb.com/manual/reference/operator/query/regex/ to figure out the query that I need.

I need to find documents in a mongo collection which has values of following format in a field:

"key->some_name::details->(value = '{wild_card_value_here}'):sort->by_name"

In SQL this query would look like

SELECT * from some_Table where field like 'key->some_name::details->(value = ''%''):sort->by_name'

Note that single quote is part of the string

Here's what I tried with mongo:

db.getCollection('collection_name').find({"some_field":{$regex:/^key->some_name::details->(value = '.*'):sort->by_name/}})

But it returns 0 documents. I also tried this which did not work either:

db.getCollection('collection_name').find({"some_field":"key->some_name::details->(value = '/.*/'):sort->by_name"})

I'm unsure if the syntax itself is issue or the special characters in the string like , -> : etc.

EDIT: Example document that I want to be found:

{
...
"some_field":"key->some_name::details->(value = 'id_1'):sort->by_name"
...
}

and

{
...
"some_field":"key->some_name::details->(value = 'id_2'):sort->by_name"
...
}

Solution

  • Turns out this was a matter of escaping special characters ( and ), The query that worked is:

    db.getCollection('collection_name').find({"some_field":{$regex:/^key->some_name::details->\(value = '.*'\):sort->by_name/}})