爲了解釋考慮了以下文件:
{
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爲了首先測試場的存在。
顯然,您將該字段設置爲「null」的文檔。 –
當count()返回意外數字時,不要使用count()並查看返回的是什麼 - 這些都是你沒有想到的文檔。 –
@SergioTulentsev不一定。看到答案。 –