Let's say I have a users collections, with a roleIds field containing an array of Role references.
db.users.aggregate([
{$match:{ _id: ObjectId('5f9453b4484d206714c02a2f') }},
{$project:{ roleIds: 1, _id: 0 }},
{$unwind: "$roleIds"},
{$lookup:{ from: "roles", localField: "roleIds", foreignField: "_id", as: "roles"}}, // <= STEP 4
{$replaceRoot: "$roles"}
])
After STEP 4, I have something like this:
{
"roles" : [
{ "_id" : ObjectId("xxxx"), "name" : "role1" },
{ "_id" : ObjectId("xxxx"), "name" : "role2" },
]
}
How can I transform it to this:
[
{ "_id" : ObjectId("xxxx"), "name" : "role1" },
{ "_id" : ObjectId("xxxx"), "name" : "role2" },
]
The replaceRoot stage seems to work only if the roles field is a document, not an array, It throws an error in this case.
{ $unwind: "$roles" }deconstruct array before$replaceRoot.