MongoDB正则表达式查询不返回任何结果

时间:2012-12-22 00:45:49

标签: mongodb mongodb-query

假设我们有一个用一个条目初始化的集合

db.test.insert({text:"why does this not work"})

所以看起来像这样

db.test.find()
{ "_id" : ObjectId("50d500b384a6859f9a9bfbc1"), "text" : "why does this not work" }

一个看起来像

的查询
db.test.find({"text":/.*why.*/})

我期待这会拿到第一张唱片,但事实并非如此。任何想法为什么不呢?

2 个答案:

答案 0 :(得分:0)

Javascript不支持'。'。请改用[\ s \ S]。这实际上意味着:无论是空间还是任何不是空间的东西。

编辑:虽然你的例子很好用。我用Javascript遇到了上述问题,[\ s \ S]修复了它。试试吧。

答案 1 :(得分:0)

它应该可以正常工作。

MongoDB shell version: 2.2.0
connecting to: test
> db.test.insert({text: "this is some sample text"})
> db.test.find()
{ "_id" : ObjectId("50d50b85499df584cc266f9a"), "text" : "this is some sample text" }
> db.test.find({text: /sample/})
{ "_id" : ObjectId("50d50b85499df584cc266f9a"), "text" : "this is some sample text" }
> db.test.find({text: /.*sample.*/})
{ "_id" : ObjectId("50d50b85499df584cc266f9a"), "text" : "this is some sample text" }

即使您的确切样本也可以使用:

> db.test.insert({text:"why does this not work"})
> db.test.find({"text":/.*why.*/})
{ "_id" : ObjectId("50d50c4c499df584cc266f9b"), "text" : "why does this not work" }

也许你忽视了别的什么?

相关问题