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

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

本文介绍了MongoDB聚合:如何检查数组中是否存在包含多个属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想检查是否存在匹配多个属性的对象.我已经尝试过使用$in$and,但是它不能按照我想要的方式工作.

I have an array of objects and I want to check if there is an object that matches multiple properties. I have tried using $in and $and but it does not work the way I want it to.

这是我当前的实现.

我有一个像这样的数组

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

我正在尝试编写聚合代码,以检查是否存在同时包含"id":2"l":"j"属性的对象.我当前的实现检查是否有一个对象包含第一个属性,然后检查是否有一个对象包含第二个属性.

I am trying to write aggregation code that can check if there is an object that contains both "id":2 and "l":"j" properties. My current implementation checks if there is an object containing the first property then checks if there is an object containing the second one.

我如何获得想要的结果?

How can I get my desired results?

下面,请参阅我的聚合查询.完整代码为此处

Below, see my aggregation query. The full code is here

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

    }
  }
])

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

The above query returns true yet there is no object in the array both of the properties id:2 and "l":"J". I know the code works as expected. How can I get my desired results?

推荐答案

您要使用 $ elemMatch

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

MongoPlayground

编辑

在聚合$project阶段,我将使用 $ filter

In an aggregation $project stage I would use $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
        ]
      }
    }
  }
])

MongoPlayground

这篇关于MongoDB聚合:如何检查数组中是否存在包含多个属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:04