Wildcard Search in MongoDB

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

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

or

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

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

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

or

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

So, if a document has a wildcard, I want to match it for criteria matching this pattern.

+4
source share
1 answer

For such wildcards, you can use a regex that looks something like this:

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

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

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

, !


, , . , .

path.replace(/foo\/bar\/(.*)\/somethingelse/, 'foo/bar/($1|{id}|\*)/somethingelse')
db.collection.find({path: new RegExp(path)})
+1

All Articles