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.
$set
- Setaddress.current
field withaddress
value.$unset
- Removecity
,state
,zip
fields fromaddress
field.
db.collection.update({},
[
{
$set: {
"address.current": "$address"
}
},
{
$unset: [
"address.city",
"address.state",
"address.zip"
]
}
],
{
multi: true
})