MongoDB regex matching trouble

孤者浪人 提交于 2019-12-07 01:03:02

问题


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:


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.



来源:https://stackoverflow.com/questions/43602310/mongodb-regex-matching-trouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!