1

I am fairly new to MongoDB and I came across the $replaceRoot(aggregation) which I need to output the document the way I need it.

Document Schema

{
name: "Apple",
image: "",
is_fruit: true,
other: [
  {
    url: "",
    quotes: { // saved as ObjectId and is then lookedup or populated
    text: "An apple a day keeps the doctor away"
  }
}
]
}

Wanted Output

{
  name: "Apple",
  image: "",
  is_fruit: true,
  other: [
    {
      text: "An apple a day keeps the doctor away"
    },
  ...
  ]
  }

i.e: To make quotes field as the root of the other array and not the root of entire document.

Thank you.

1
  • 1
    I don't really get what you're trying to achieve here. Are you trying to limit the number of returned fields inside the array? Or where do the ´url´ and ´quotes´ field go to? Commented Feb 15, 2018 at 13:25

2 Answers 2

1

There is no $replaceRoot like for embedded array but you can achieve similar effect using $map to transform the array into new format.

Something like

db.col.aggregate([
  {
    "$addFields": {
      "other": {
        "$map": {
          "input": "$other",
          "as": "res",
          "in": {
            "text": "$$res.text"
          }
        }
      }
    }
  }
])

You can easily do something similar in client side code.

Sign up to request clarification or add additional context in comments.

Comments

0

By using $replaceRoot(aggregation) here is the output. P.S: The collection name I used is 'demoStack' replace it with your specific collections.

enter image description here

Query is :

db.demoStack.aggregate([
{ $replaceRoot: { newRoot: { $mergeObjects: [ 
    {name:"$name"},
    { image: "$image" },
    {is_fruit:"$is_fruit"},
    {other:"$other.quotes"}        
    ] } } } ])

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.