我有一个restaurants
包含3772页的文档集合,我试图找到包含在元素中的所有文件grades
,有一个数组score
的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个文档。
从上的文档中$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"
}
您在MongoDB中通过在一个对的事情{
,并}
为JavaScript对象。在javascript对象中,每个键只能有一个值。
该表达式{score: {$gt: 80}, score: {$lt: 100}}
尝试将两个不同的值分配给同一键score
,因此一个将覆盖另一个。结果被解释为简单{score: {$lt: 100}}
。
您的第二个查询应根据您的描述为您提供所需的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句