Reputation: 107
I have subdocuments inside documents. And I'm trying to get entire documents if any subdocument provides multiple conditions. It's working right except not showing unmatched subdocuments.
# EXAMPLE DOCUMENT
name: "Sam",
specs: [
{city: "istanbul", color: "blue"},
{city: "istanbul", color: "black"},
{city: "izmir", color: "yellow"}
]
# QUERY
Dudes.aggregate([
{$unwind: '$specs'},
{$match: {'specs.city': "istanbul", 'specs.color': "yellow"} }
]);
It's returning the matching documents but in documents there is only matched subdocument.
# OUTPUT:
name: "Sam",
specs: [
{city: "izmir", color: "yellow"}
]
Upvotes: 1
Views: 175
Reputation: 57105
Updated Demo - https://mongoplayground.net/p/J1GF0ErYNEk
Use $elemMatch to match object inside the array element.
db.collection.find({
specs: {
$elemMatch: {
"city": "istanbul",
"color": "blue"
}
}
});
Demo - https://mongoplayground.net/p/Wr1L6i2dipP
You can directly use $match
and remove {$unwind: '$specs'}
db.collection.aggregate([
{
$match: {
"specs.city": "istanbul",
"specs.color": "blue"
}
}
]);
Upvotes: 2