MongoDB Aggregation: How to check if an object containing multiple properties exists in an array

Viewed 703

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.

Here is my current implementation.

I have an array like

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

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"
            ]
          }
        ]
      },
      
    }
  }
])

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?

1 Answers

You want to use something like $elemMatch

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

MongoPlayground


EDIT

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

Related