2014-02-24 38 views
1

我想match a field without specifying an array index用下面的查詢:爲什麼查詢文檔使用值'null`錯誤地匹配子文檔數組中的字段?

db.games.find({ 'players.userId': userId }) 

其中userId是字符串或者是null如果沒有用戶登錄我預計上述光標count()0userId === null,但我發現情況並非如此 - 計數所有players爲空數組[]的文檔。我認爲players.userId可能是undefined,但不是null。這裏發生了什麼? mongo是否使用==而不是===,強制undefinednull的值是否相同?

+1

顯然,您將該字段設置爲「null」的文檔。 –

+0

當count()返回意外數字時,不要使用count()並查看返回的是什麼 - 這些都是你沒有想到的文檔。 –

+0

@SergioTulentsev不一定。看到答案。 –

回答

2

爲了解釋考慮了以下文件:

{ 
    name: "PacMan", 
    players: [ { userId: "Bill" }, { userId: "Ted" }, { userId: "Death" } ] 
} 
{ 
    name: "Frogger", 
    players: [ { userId: null }, { userId: "Bill" }, { userId: null } ] 
} 
{ 
    name: "Defender", 
    players: [ ] 
} 

如果發出類似的查詢:

>db.games.find({ "players.userId" : "Bill" }) 

{ 
    name: "PacMan", 
    players: [ { userId: "Bill" }, { userId: "Ted" }, { userId: "Death" } ] 
} 
{ 
    name: "Frogger", 
    players: [ { userId: null }, { userId: "Bill" }, { userId: null } ] 
} 

你會得到兩個文件,你想到的是與存在於該用戶id玩家陣列。但是,如果我們改變,要null

>db.games.find({ "players.userId" : null }) 

{ 
    name: "Frogger", 
    players: [ { userId: null }, { userId: "Bill" }, { userId: null } ] 
} 
{ 
    name: "Defender", 
    players: [ ] 
} 

等一下,你得到你所沒想到的文檔。玩家陣列中沒有元素。那麼爲什麼它匹配?讓我們來看看這種形式:

>db.games.find({ "players.userId" : {$exists: true } }) 
{ 
    name: "PacMan", 
    players: [ { userId: "Bill" }, { userId: "Ted" }, { userId: "Death" } ] 
} 
{ 
    name: "Frogger", 
    players: [ { userId: null }, { userId: "Bill" }, { userId: null } ] 
} 

現在,讓我們產生players.userId實際上那裏,第三文件將不被包括在內,因爲它有符合這個條件,沒有項目。所以,最後才考慮的最後形式:

>db.games.find({ $and: [ 
    {"players.userId" : {$exists: true }}, 
    {"players.userId": null } 
] }) 

{ 
    name: "Frogger", 
    players: [ { userId: null }, { userId: "Bill" }, { userId: null } ] 
} 

這將找到的結果whsere有存在的領域,它有一個null值。

所以總結一下。即使數組不包含任何與null值測試相匹配的元素,它仍然可能會返回,因爲null條件被認爲是真實的,因爲空項目評估爲null。如果你想排除這種情況下,那麼你使用$exists爲了首先測試場的存在。

+0

謝謝。然而,我很疑惑查詢會匹配空數組,因爲這些數組不包含要匹配的元素。 –

+0

@DonnyWinston重新閱讀答案。根據我使用的條款搜索文檔。這並不令人困惑,有一個真正的原因是爲什麼這樣。最好你瞭解自己的發展。 –

相關問題