How to check array element is identical in mongodb query?

24 Views Asked by At

I have the following collection:

[
  {
    "_id": 1,
    "favorite": {
      "color": "red",
      "foods": {
        "fruits": "banana",
        "fastfood": [
          "burger",
          "sandwich"
        ]
      }
    }
  },
  {
    "_id": 2,
    "favorite": {
      "color": "green",
      "foods": {
        "noodles": "ramen",
        "fastfood": [
          "fries",
          "burger",
          "corn dog"
        ]
      }
    }
  },
  {
    "_id": 3,
    "favorite": {
      "color": "red",
      "foods": {
        "soup": "cream soup"
      }
    }
  }
]

And I have to following query:

db.collection.find({
  "favorite.foods.fruits": "banana",
  "favorite.foods.fastfood": {
    "$all": [
      "burger"
    ]
  }
})

Current Result:

[
  {
    "_id": 1,
    "favorite": {
      "color": "red",
      "foods": {
        "fastfood": [
          "burger",
          "sandwich"
        ],
        "fruits": "banana"
      }
    }
  }
]

Expected Result: But this is not my expected result. I need to match full favorite.foods.fastfood object for fastfood array. If the fastfood is NOT Identical to my query the query should return null/false/empty.

Additionally query result with mongoTemplate is also fine for me.

2

There are 2 best solutions below

5
ray On BEST ANSWER

Just use $setEquals to perform the array comparison.

db.collection.find({
  $expr: {
    $let: {
      vars: {
        fruits_input: "banana",
        fastfood_input: [
          "burger"
        ]
      },
      in: {
        $and: [
          {
            $eq: [
              "$$fruits_input",
              "$favorite.foods.fruits"
            ]
          },
          {
            "$setEquals": [
              "$$fastfood_input",
              "$favorite.foods.fastfood"
            ]
          }
        ]
      }
    }
  }
})

Mongo Playground

4
user20042973 On

If order matters for the purposes of being identical, then simply remove the $all operator:

db.collection.find({
  "favorite.foods.fruits": "banana",
  "favorite.foods.fastfood": [
    "burger"
  ]
})

Playground demonstration