2014-02-11 32 views
0

我在我的test數據庫中有這個集合。MongoDB - 在嵌入式文檔上發現奇怪的行爲

[test] 2014-02-11 18:45:48.338 >>> db.blog.posts.find(); 
{ 
     "_id" : ObjectId("52ee29bdb8eb94049427886a"), 
     "comments" : [ 
       { 
         "author" : "Jane", 
         "comment" : "yes, yes, it is", 
         "votes" : 5 
       } 
     ], 
     "content" : "This is a post", 
     "id" : 5 
} 
{ 
     "_id" : ObjectId("52f95c5bd1fe9c171fe4344b"), 
     "comments" : [ 
       { 
         "author" : "Jane", 
         "comment" : "yes, yes, it is", 
         "votes" : 5 
       }, 
       { 
         "author" : "Nick", 
         "comment" : "test", 
         "votes" : 10 
       }, 
       { 
         "author" : "John", 
         "comment" : "new one", 
         "votes" : 4 
       } 
     ], 
     "content" : "This is a post", 
     "id" : 5 
} 

當我運行此查找查詢:

[test] 2014-02-11 18:45:50.318 >>> db.blog.posts.find({ "comments" : {author : "Jane", comment: "yes, yes, it is", votes: 5}}); 

我得到兩個文件了。

但是,如果我運行此查找查詢

[test] 2014-02-11 18:46:18.428 >>> db.blog.posts.find({ "comments" : {author : "Jane", comment: "yes, yes, it is", votes: {$gte : 5}}}); 

我沒有得到任何文件了。

這是爲什麼?如何來== 5給我結果回來,但> = 5不返回任何東西。

回答

1

非常有趣的情況,說實話。但是,我認爲
是更有效的命令來獲得你所需要的。

我已經解決了您的問題,如下所示。

db.posts.find({ 
"comments": { 
    "$elemMatch": { 
     author : "Jane", 
     comment: "yes, yes, it is", 
     votes: {"$gte" : 5} 
    } 
    } 
}); 

,結果如下:

enter image description here

究其原因,第一OP查詢工作和第二OP查詢不會是因爲
在第一種情況下有文件符合被查詢的確切形式。
第二個OP查詢使用修飾符,因此需要使用$ elemMatch換行。從官方網站的MongoDB

更多信息可以在這裏找到:
http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/

希望這有助於。

+1

非常好。也許這將有助於解釋第一個查詢起作用的原因,而第二個查詢不起作用,因爲在第一種情況下,存在滿足被查詢的*確切*表單的文檔。第二種情況使用*修飾符*,因此需要用** $ elemMatch ** –

+0

@NeilLunn包裝謝謝並感謝那位太太的回答。 –