2014-10-08 44 views
1

这里的测试用例:MongoDB的正则表达式不一致

db.test.insert({ name: "john"}); 
db.test.insert({ name: "donny"}); 
db.test.insert({ name: "lenny"}); 

db.test.find({ name: { $regex: /^((?!nn)[\s\S])*$/}}); //works fine, returns only john 
db.test.find({ name: { $regex: new RegExp("/^((?!nn)[\s\S])*$/")}}); //returns nothing 

正则表达式应该返回未方含“NN”对象,但用RegExp对象时,它不无法正常工作。我使用Robomongo测试了这个。

任何想法为什么?

回答

2

使用new RegExp时,不要包含前导和尾随/个字符。这些仅用于JavaScript中的文字符号。您还需要在字符串中避开反斜杠。

db.test.find({ name: { $regex: new RegExp("^((?!nn)[\\s\\S])*$")}});