0

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"
...
}
Sarvo
  • 111
  • 1
  • 6
  • 1
    It is advisable to add an example of the document you are expecting to be found. Ideally if it is not a whole but a stripped-down version with only fields sufficient to reproduce your results, in your case it seems to be "some_field". It also won't harm to practise your regex skills in isolation, e.g. on https://regex101.com/. I'd say `(` and `)` are better candidates to the special characters – Alex Blex Jul 17 '19 at 15:03
  • @AlexBlex You were right, it was the special characters `( )` – Sarvo Jul 17 '19 at 15:27

1 Answers1

0

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/}})
Sarvo
  • 111
  • 1
  • 6