3

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.

2
  • can you provide some sample documents? Commented Oct 24, 2020 at 17:07
  • 2
    { $unwind: "$roles" } deconstruct array before $replaceRoot. Commented Oct 24, 2020 at 17:14

1 Answer 1

5

This works:

db.users.aggregate([
  {$match:{ _id: ObjectId('5f9453b4484d206714c02a2f') }}, 
  {$project:{ roleIds: 1, _id: 0 }}, 
  {$unwind: "$roleIds"}, 
  {$lookup:{ from: "roles", localField: "roleIds", foreignField: "_id", as: "roles"}},
  {$unwind: "$roles"},
  {$replaceRoot: { newRoot: "$roles" }}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.