MongoDB 聚合:如何检查数组中是否存在包含多个属性的对象

2024-05-18

我有一个对象数组,我想检查是否有一个对象与多个属性匹配。我尝试过使用$in and $and但它并没有按照我想要的方式工作。

这是我当前的实现。 https://mongoplayground.net/p/dEQp2Q4DW0j

我有一个像这样的数组

"choices": [
    {
        "name": "choiceA",
        "id": 0,
        "l": "k"
    },
    {
        "name": "choiceB",
        "id": 1,
        "l": "j"
    },
    {
        "name": "choiceC",
        "id": 2,
        "l": "l"
    }
]

我正在尝试编写聚合代码来检查是否存在包含两者的对象"id":2 and "l":"j"特性。我当前的实现检查是否存在包含第一个属性的对象,然后检查是否存在包含第二个属性的对象。

我怎样才能得到我想要的结果?

下面,请参阅我的聚合查询。完整的代码是here https://mongoplayground.net/p/dEQp2Q4DW0j

db.poll.aggregate([
  {
    "$match": {
      "_id": 100
    }
  },
  {
    $project: {
      numberOfVotes: {
        $and: [
          {
            $in: [
              2,
              "$choices.id"
            ]
          },
          {
            $in: [
              "j",
              "$choices.l"
            ]
          }
        ]
      },
      
    }
  }
])

上面的查询返回 true,但数组中没有对象这两个属性id:2 and "l":"J"。我知道代码按预期工作。我怎样才能得到我想要的结果?


你想使用类似的东西$elemMatch https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

db.collection.find({
  choices: {
    $elemMatch: {
      id: 2,
      l: "j"
    }
  }
})

蒙戈游乐场 https://mongoplayground.net/p/6CAU8EPntmT


EDIT

在聚合中$project我会使用的阶段$filter https://docs.mongodb.com/manual/reference/operator/aggregation/filter/

db.poll.aggregate([
  {
    "$match": {
      "_id": 100
    }
  },
  {
    $project: {
      numberOfVotes: {
        $gt: [
          {
            $size: {
              $filter: {
                input: "$choices",
                as: "choice",
                cond: {
                  $and: [
                    {
                      $eq: [
                        "$$choice.id",
                        2
                      ]
                    },
                    {
                      $eq: [
                        "$$choice.l",
                        "j"
                      ]
                    }
                  ]
                }
              }
            }
          },
          0
        ]
      }
    }
  }
])

蒙戈游乐场 https://mongoplayground.net/p/G26ZnCLOA8z

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB 聚合:如何检查数组中是否存在包含多个属性的对象 的相关文章

随机推荐