2012-03-20 85 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()