理解$不与MongoDB中的$elemMatch结合

问题描述 投票:0回答:1

我有这个文档结构:

{
      "name": "ab",
      "grades": [
        {
          "grade": "A",
          "score": 1
        },
        {
          "grade": "A",
          "score": 12
        },
        {
          "grade": "A",
          "score": 7
        }
      ],
      "borough": "Manhattan2"
    }

作业是写一个查询,找出所有等级评分都大于5的餐厅。

问题的解决方法如下:

db.restaurants.find({
      "grades": {
        "$not": {
          "$elemMatch": {
            "score": {
              "$lte": 5
            }
          }
        }
      }
    })

我无法理解建议的解决方案。

到目前为止,我只使用

$elemMatch
来匹配数组的至少一个元素或数组内部对象中的元素(
grades.score
),但是
$not
到底是如何“以某种方式制作”
$elemMatch
来检查 all
grades.score
在这个对象中?

我确实理解一般思想,“不要看分数小于等于5,剩下的就是我们需要的”,但我无法理解这段代码返回什么:

"$not": {
      "$elemMatch": {
        "score": {
          "$lte": 5
        }
      }
    }

如果在运行和测试之前被问到这个查询会做什么,我会说它首先找到大于 5 的

score
并获取该文档,但这是错误的,我无法弄清楚为什么。我发现字段和关键字的顺序发挥了一些作用,但没有看到其中的联系。

mongodb mongodb-query
1个回答
0
投票

{ "$elemMatch": { "score": { "$lte": 5 } } }
将匹配具有 至少一个数组元素
score <= 5
的文档。

  • 因此
    $not
    将匹配那些 不符合该标准的文档
  • 即“没有一个元素具有
    score <= 5
  • 这与“所有元素都有
    score > 5
    ”相同
© www.soinside.com 2019 - 2024. All rights reserved.