首页 文章

MongoDB:$ elemMatch问题

提问于
浏览
1

我有一个包含3772个文档的 restaurants 集合,我试图找到包含 grades 数组中 score80 < 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 运算符)似乎与第二个查询的执行方式不同 . 为什么会出现差异?

Example document:

{
"_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"
}

1 回答

  • 2

    您在一对 {} 中传递MongoDB中的内容是javascript对象 . 在javascript对象中,每个键只能有一个值 .

    表达式 {score: {$gt: 80}, score: {$lt: 100}} 尝试将两个不同的值分配给同一个键 score ,因此一个会覆盖另一个 . 结果被解释为简单 {score: {$lt: 100}} .

    您的第二个查询应该根据您的描述为您提供所需的结果 .

相关问题