Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard Search in MongoDB

Can someone please help me with the following wildcard search criteria in MongoDB ? Document:

{"path":"foo/bar/{id}/somethingelse"}

or

{"path":"foo/bar/*/somethingelse"}

So I want to get this document when a find request something like this comes:

db.collection.find({path:"foo/bar/1/somethingelse"})

or

db.collection.find({path:"foo/bar/2/somethingelse"})

So if the document has got some wildcard, I want to match it for a criteria matching that pattern.

like image 551
Abhijeet Avatar asked Oct 31 '22 01:10

Abhijeet


1 Answers

For wildcards like this, you can use regex which would look something like:

db.collection.find({"path": new RegExp("foo/bar/.*?/somethingelse")})

But if I understand your question correctly, you have a single document in your collection with a path of {"path":"foo/bar/{id}/somethingelse"} and you want to return it if the query is actually for db.collection.find({path:"foo/bar/1/somethingelse"}). To do this, its likely best that you do search replaces prior to the search to change the actual query like so.

path = path.replace(/foo\/bar\/(.*)\/somethingelse/, 'foo/bar/{id}/somethingelse')
db.collection.find({path:path})

Hope this helps!


edit based on comments

To do a reverse wildcard match the following should work, returning the requested document and any matching wildcards. You'll need to define what each actual wildcards are for this to work.

path.replace(/foo\/bar\/(.*)\/somethingelse/, 'foo/bar/($1|{id}|\*)/somethingelse')
db.collection.find({path: new RegExp(path)})
like image 169
Ian Belcher Avatar answered Nov 11 '22 06:11

Ian Belcher