Home > Back-end >  How to flatted nested keys into the top level object in Mongoose
How to flatted nested keys into the top level object in Mongoose

Time:05-06

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.

CodePudding user response:

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

  • Related