Reputation: 769
I want to do a lookup using the ObjectId in thing.subCategory
on the nested category.subCategories
array to find the corresponding object in that array.
I have an aggregation that currently generates this:
{
_id: ObjectId("...")
thing: {
category: ObjectId("001"),
subCategory: ObjectId("123")
},
category: {
id: ObjectId("001"),
title: "Some Category",
subCategories: [
{
_id: ObjectId("123"),
title: "Some Subcategory I want"
},
{
_id: ObjectId("124"),
title: "another subcategory"
}
]
}
}
And I want to get to:
{
_id: ObjectId("...")
thing: {
category: ObjectId("001"),
subCategory: ObjectId("123")
},
category: {
id: ObjectId("001"),
title: "Some Category",
subCategories: [...]
},
subCategory:
{
_id: ObjectId("123"),
title: "Some Subcategory I want"
}
}
Thanks for any help!
Upvotes: 0
Views: 27
Reputation: 36104
$filter
to iterate loop of category.subCategories
and filter matching category
$arrayElemAt
to get first element from filtered categorydb.collection.aggregate([
{
$addFields: {
subCategory: {
$arrayElemAt: [
{
$filter: {
input: "$category.subCategories",
cond: { $eq: ["$$this._id", "$thing.category"] }
}
},
0
]
}
}
}
])
Upvotes: 1