3

I have documents like so:

[
  {
    title: 'apple',
    attributes: {
      colour: 'red',
      kind: 'fruit'
  },
  {
    title: 'broccoli',
    attributes: {
      colour: 'green',
      kind: 'vegetable'
    }
  },
]

In my aggregation pipeline, I want to essentially flatten the hierarchy one level deep, such that it looks like this:

[
  {
    title: 'apple',
    colour: 'red',
    kind: 'fruit'
  },
  {
    title: 'broccoli',
    colour: 'green',
    kind: 'vegetable'
  }
]

The thing is, the keys in the nested object are dynamic across documents, so I wouldn't be able to $project them statically. I need to dynamically pull these nested key/value pairs to the top object.

1 Answer 1

6

Maybe something like this using the aggregation framework:

db.collection.aggregate([
{
 $replaceRoot: {
  newRoot: {
    $mergeObjects: [
      "$$ROOT",
      "$attributes"
    ]
   }
  }
 },
 {
 $project: {
   attributes: 0
   }
 }
])

Explained:

  1. ReplaceRoot with merged object between the root object & attributes
  2. Remove the attributes object from the output.

playground

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.