Reputation: 267
I need your help to get data from collection with and condition. Suppose I have a collection having below document and I need search on sub document field named brandId having value of 14 and 38.
{
"_id" : ObjectId("5b3b206c4a25da19d05f41a2"),
"models" : [
{
"brandId" : "14",
"modelId" : "100",
"brandSlug" : "honda",
"modelSlug" : "hrv"
},
{
"brandId" : "38",
"modelId" : "894",
"brandSlug" : "toyota",
"modelSlug" : "fortuner"
},
{
"brandId" : "38",
"modelId" : "894",
"brandSlug" : "toyota",
"modelSlug" : "fortuner"
},
{
"brandId" : "37",
"modelId" : "773",
"brandSlug" : "suzuki",
"modelSlug" : "ertiga"
}
]
}
I want that sub documents which brandId is 14 and 38.
Desired Output =>
{
"_id" : ObjectId("5b3b206c4a25da19d05f41a2"),
"models" : [
{
"brandId" : "14",
"modelId" : "100",
"brandSlug" : "honda",
"modelSlug" : "hrv"
},
{
"brandId" : "38",
"modelId" : "1240",
"brandSlug" : "toyota",
"modelSlug" : "kijang-innova"
},
{
"brandId" : "38",
"modelId" : "894",
"brandSlug" : "toyota",
"modelSlug" : "fortuner"
}
]
}
Upvotes: 1
Views: 113
Reputation: 4343
Why be so complicated? Unwind,match and group will do the job perfectly.
db.test1.aggregate([
{
$unwind: {
path : "$models"
}
},
{
$match: {
$or:[{"models.brandId":"14"},{"models.brandId":"38"}]
}
},
{
$group: {
_id:"$_id",
models:{$push:"$models"}
}
},
]
);
Upvotes: 1