mongodbnosqlmongotemplate

How to check array element is identical in mongodb query?


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.


Solution

  • 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