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
If order matters for the purposes of being identical, then simply remove the
$all
operator:Playground demonstration
Just use
$setEquals
to perform the array comparison.Mongo Playground