Home > Net >  Add extra level of nesting to existing data?
Add extra level of nesting to existing data?

Time:10-21

In my database, I have data that lives in a single level structure. However, I have recently made changes and I now need to convert one of the properties to a nested object for existing data.

What is the best way to query and update these existing records?

Old structure:

{
  "id": "xxx",
  "address": {
    "city": "Some City",
    "state": "AK",
    "zip": "55555"
  },
  "type": "customer"
}

New structure (need to update the old structure to look like this)

{
  "id": "xxx",
  "address": {
    "current": {
      "city": "Some City",
      "state": "AK",
      "zip": "55555"
    }
  },
  "type": "customer"
}

In the above example, I want to update everyone's address to add the extra layer of nesting with the current property.

CodePudding user response:

You need Update with aggregation pipeline.

  1. $set - Set address.current field with address value.
  2. $unset - Remove city, state, zip fields from address field.
db.collection.update({},
[
  {
    $set: {
      "address.current": "$address"
    }
  },
  {
    $unset: [
      "address.city",
      "address.state",
      "address.zip"
    ]
  }
],
{
  multi: true
})

Sample Mongo Playground

  • Related