I'm using MongoDB v5 with NodeJS (no Mongoose).
Let's say I have a collection structured the following way. This specific setup (an ObjectId nested inside an object contained inside an array contained inside another object) is trickier to handle in an aggregation because nested.users can not be unwinded then rebuilt again into an array (because $group doesn't support deep properties) and using $lookup with let/as/pipeline works only if as contains something different than nested.users.user, in which case the object loses it's original shape.
{
nested: {
users: [
{
user: ObjectId('...'),
status: 'pending',
},
{
user: ObjectId('...'),
status: 'pending',
},
]
}
}
I need to rebuild the document to populate nested.users.user (while preserving it's original shape) by using a single aggregation pipeline. I expect the following outcome:
{
nested: {
users: [
{
user: {
_id: ObjectId('...'),
name: 'User 1',
},
status: 'pending',
},
{
user: {
_id: ObjectId('...'),
name: 'User 2',
},
status: 'approved',
},
]
}
}
Reshaping the data is not an option. This is just an example of a more general problem I'm experiencing. I need a programmactic way to populate ObjectIds nested inside arrays inside objects in different collections.
So far I've tried:
- unwinding and rebuilding
nested.usersinto an array - using
$lookupwithpipelinecombined with$replaceRoot, couldn't reassemblenested.users