2016-08-23 40 views
1

我的mongo集合foo有一系列文檔,其中一些文檔中有一個名爲music的數組,其中一些包含值「Blues」。

如果我想顯示數組存在的所有記錄,並且它們不包含單詞Blues,爲什麼這不起作用(它似乎忽略了第一個標準)?

db.foo.find({ 
    music: { $exists: true }, 
    music: { $nin: ["Blues"] } 
}) 

,但這樣做:

db.foo.find({ 
    music: { 
     $exists: true, 
     $nin: ["Blues"] 
    } 
}) 

回答

1

還沒有嘗試,但你需要添加$和你query.Otherwise它僅適用的最後一條語句。

db.foo.find ($and:[{music : {$exists : true}}, {music : {$nin : ["Blues"]}}}]) 
+0

好主意,但它應該是'db.foo.find({$ and:[{music:{$ exists:true}},{music:{$ nin:[「Blues」]}}]}) ':) – Messa

+0

是的,我還沒有嘗試代碼,只是想指出,問題是他錯過了「$和」 –

1

由於編程語言中的結構規則。語法:

db.foo.find({ 
    music: { $exists: true }, 
    music: { $nin: ["Blues"] } 
}) 

,最好的辦法去想這個(雖然這取決於驅動器和這裏的語言)是:

create an object with "music: { $exists: true }" and then add "music: { $nin: ["Blues"] }" to it 

後者將覆蓋前面

2

因爲

> var obj = {music: 1, music: 2}; 
> obj 
Object {music: 2} 

它也類似於

> var obj = {}; 
> obj.music = 1; 
> obj.music = 2; 

然後期待obj.music在某種程度上都是12