'How to flatted nested keys into the top level object in Mongoose

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R2D2