2012-03-20 97 views
64

我想其中一个文本字段没有显示在MongoDB中查询“”(空白)的MongoDB不等于

{ 'name' : { $not : '' }} 

但是我得到invalid use of $not

我看过了错误文档但他们使用的示例适用于复杂的案例(使用regexp和$not否定另一个操作员)。

我该怎么做我想要做的简单事情?

回答

97

使用$ne - $not应遵循的标准操作:

为$ NE的例子,它代表不等于:

use test 
switched to db test 
db.test.insert({author : 'me', post: ""}) 
db.test.insert({author : 'you', post: "how to query"}) 
db.test.find({'post': {$ne : ""}}) 
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" } 

现在$没有,这发生在谓语( $ NE)和取消它($没有):

db.test.find({'post': {$not: {$ne : ""}}}) 
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" } 
+2

对于那些好奇'$ ne'是指“不等于”。 – abraham 2012-06-22 14:59:41

+1

这个答案有很多票数,但是解释很不清楚。这个例子中有$ not和$ ne的情况是怎么回事? – GaTechThomas 2015-05-04 22:18:34

+0

@GaTechThomas有所改进,现在还不清楚吗? – 2015-05-04 22:54:17

44

如果你想要做多$ne然后做

db.users.find({name : {$nin : ["mary", "dick", "jane"]}}) 
-1

真实生活中的例子;找到所有而不是当前用户:

var players = Players.find({ my_x: player.my_x, my_y: player.my_y, userId: {$ne: Meteor.userId()} }); 
2

Mongo docs

$not操作只影响其他运营商不能独立检查 领域和文件。因此,使用$not运算符为 逻辑分隔符和$ne运算符来直接测试 字段的内容。

由于要测试现场直接$ne是在这里使用合适的运营商。

编辑:

,你想用$not的情形是:

db.inventory.find({ price: { $not: { $gt: 1.99 } } }) 

这将选择所有文件,其中:

  • 价格字段中的值小于或等于1。99或价格
  • 字段不存在
0

如果阵列中的一个null并且要避免:

db.test.find({"contain" : {$ne :[] }}).pretty()