I’m using MongoDb version 5.0.6.
I have this structure:
{
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
"data": {
"user": [
{"country": "Netherlands", "originalCountry": "Denmark"},
{"country": "France", "originalCountry": "Denmark"},
]
},
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
"data": {
"user": [
{"country": "ITALIE", "originalCountry": "ITALIE"},
{"country": "France", "originalCountry": "France"},
]
}
},
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
"data": {
"user": [
{"country": "UK", "originalCountry": "CANADA"},
{"country": "France", "originalCountry": "France"},
]
}
}
I wish to find only the documents that have country
equal to supplierCountry
in this case:
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
"data": {
"user": [
{"country": "ITALIE", "originalCountry": "ITALIE"},
{"country": "France", "originalCountry": "France"},
]
}
}
I have tried with this query
db.collection.find({
"data.user": {
$elemMatch: {
"country": {
$ne: "$data.user.originalCountry"
}
}
}
})
but the result is not right.
2
Answers
By using
$map
, you can project thedata.user
array to an array of boolean by comparing the 2 country fields. Then, use$allElementsTrue
to find documents that have all array entries true. (i.e. all array entries are having same country)Mongo Playground
You can use aggregation. This will compare the 2 values
country
andoriginalCountry
in the sameuser
object array and return those documentsMongo Playground: https://mongoplayground.net/p/OhJXK7CC3HX