2016-05-14 217 views
1

我有一個包含3772個文檔的restaurants集合,我試圖找到grades數組中包含的80 < score < 100的元素的所有文檔。

然而,我注意到,有以下兩個查詢之間有很大的差異:

db.restaurants.find(
{"grades": 
    {$elemMatch: {score: {$gt: 80}, score: {$lt: 100}}} 
} 
) 

返回所有的文件,而

db.restaurants.find(
{"grades": 
    {$elemMatch: {score: {$gt: 80, $lt: 100}}} 
} 
) 

回報只是3個文件。

documentation$elemMatch,它指出

的$ elemMatch操作者匹配包含與所有指定的查詢條件匹配的至少一個元素的數組字段的文檔。

但是,我注意到,第一個查詢(行爲像$and運營商)似乎執行不同的第二個查詢。爲什麼會有差異?

實施例的文檔:

{ 
"_id" : ObjectId("57290430139a4a37132ca096"), 
"address" : { 
    "building" : "345", 
    "coord" : [ 
     -73.9864626, 
     40.7266739 
    ], 
    "street" : "East 6 Street", 
    "zipcode" : "10003" 
}, 
"borough" : "Manhattan", 
"cuisine" : "Indian", 
"grades" : [ 
    { 
     "date" : ISODate("2013-05-30T00:00:00Z"), 
     "grade" : "A", 
     "score" : 12 
    }, 
    { 
     "date" : ISODate("2012-04-06T00:00:00Z"), 
     "grade" : "C", 
     "score" : 92 
    }, 
    { 
     "date" : ISODate("2011-11-03T00:00:00Z"), 
     "grade" : "C", 
     "score" : 41 
    } 
], 
"restaurant_id" : "40381295" 
} 

回答

2

你MongoDB中傳遞1對{}的事情是JavaScript對象。在一個javascript對象中,每個鍵只能有一個值。

表達式{score: {$gt: 80}, score: {$lt: 100}}試圖將兩個不同的值分配給同一個鍵score,因此一個覆蓋另一個。結果被解釋爲{score: {$lt: 100}}

你的第二個查詢應該根據你的描述給你想要的結果。