2

If I have a document, which contains an embedded object as a value of one of its fields, like this:

{ _id: ObjectId("..."), embeddedObject: { k1: "val1", k2: "val2", k3: "val3" } }

then how can I retrieve the embedded object itself as an output document with aggregation framework (pipeline operators)? Or it's not possible?

I.e., I need finally to get just the following result:

{ k1: "val1", k2: "val2", k3: "val3" }

Although operators $project, $match, $unwind, $group solve the close issues, none of them seems to be able to help precisely with my aforementioned request.

1 Answer 1

2

This can be achieved using one the aggregation pipeline operator $replaceRoot

  db.[collection].aggregate( [
       {
         $replaceRoot: { newRoot: "$embeddedObject" }
       }
    ] );

This will result in below output :

{ k1: "val1", k2: "val2", k3: "val3" }
Sign up to request clarification or add additional context in comments.

1 Comment

Superb. Helped. Exactly what I needed. Thanks for a prompt reply!

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.