db.foo.findOne() { "_id" :...">

MongoDB regex issues

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:[az]+/}) { "_id" : ObjectId("58fedc47622e89329d123ee8"), "path" : "a:b" } { "_id" : ObjectId("58fedc57622e89329d123ee9"), "path" : "a:b:c" } 

Obviously, the regular expression /a:[^:]+/ and /a:[az]+/ should not match the string 'a:b:c' , but it seems like Mongo failed to execute this regular expression, somebody knows what happened here?

It was sent to Jira's MongoDB as a big code , so is this an error in the MongoDB query structure?

+5
source share
1 answer

Partial matching problem, since you are not restricting the regular expression for the whole word, the partial matching existing in a:b:c , i.e. a:b , results in this document.

Use the following regex with ^$ , which are anchors to indicate the beginning and end of a word;

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

This will force the regex to apply to the entire string and ignore partial matches, as described above. For more on regex anchors, click here .

So, in general, there is no mistake, just the misuse of the regular expression.

+8
source

Source: https://habr.com/ru/post/1267115/


All Articles