skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search