2016-05-14 137 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}}

你的第二个查询应该根据你的描述给你想要的结果。