MongoDB RegExp不一致

这里是testing用例:

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 

正则expression式应该返回不包含“nn”的对象,但在使用RegExp对象时不起作用。 我使用Robomongotesting了这个。

任何想法为什么?

使用new RegExp时不要包含前导字符和尾随/字符。 这些只能用于JavaScript中的文字符号。 你还需要避开string中的反斜杠。

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