Home > Software design >  How to flatten a nested object in MongoDB?
How to flatten a nested object in MongoDB?

Time:07-27

I have a document of the form:

{
  "employee_addr": {
    "city": "London",
    "street": "Downing Street",
    "apartment": 10
  }

  "age": 58,
  "name": "Boris"
}

I want to flatten the document. That is, removing the employee_addr nested object and moving its properties to the root of the document.

This document is the result of an aggregation pipeline and I need to add another step to it

How can I do it?

Thanks!

CodePudding user response:

  1. $replaceRoot - Replace the input document with new document.

    1.1. $mergeObjects - Merge ROOT document with employee_addr object.

  2. $unset - Remove employee_addr field.

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$$ROOT",
          "$employee_addr"
        ]
      }
    }
  },
  {
    $unset: "employee_addr"
  }
])

Sample Mongo Playground

CodePudding user response:

One option is using $set if you have only several fields to flatten or you want to flatten an object but not necessarily down to the root:

db.collection.aggregate([
  {
    $set: {
      city: "$employee_addr.city",
      street: "$employee_addr.street",
      apartment: "$employee_addr.apartment",
      employee_addr: "$$REMOVE"
    }
  }
])

See how it works on the playground example.

Oterwise, use @YongShun answer, which I was about to write, but @YongShun beat me to it :)

  • Related