7

Here is my MongoDB shell session;

> db.foo.save({path: 'a:b'})
WriteResult({ "nInserted" : 1 })

> db.foo.findOne()
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }

> db.foo.save({path: 'a:b:c'})
WriteResult({ "nInserted" : 1 })

> db.foo.find({path: /a:[^:]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }

> db.foo.find({path: /a:[a-z]+/})
{ "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" }
{ "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" }

Clearly the regex /a:[^:]+/ and /a:[a-z]+/ shouldn't match string 'a:b:c', but looks like Mongo failed on this regex, does anyone know what happened here?

It was submitted to MongoDB Jira, as a bug ticket, so is it a bug within MongoDB querying structure?

1 Answer 1

9

The trouble is with the partial matching, since you are not restricting the regex for the whole word, the partial match that exists in a:b:c that is a:b is resulting in you getting that document.

Use the following regex with ^$ that are anchors to represent beginning and the end of the word;

db.foo.find({path: /^a:[^:]+$/})
db.foo.find({path: /^a:[a-z]+$/})

This will make the regex apply for the whole string, and ignore the partial matches as explained above. For more on regex anchors, click here.

So, in summary, there is no bug, just a misuse of regex.

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

Comments

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.