Reputation: 785
I have a mongo collection that looks like this.
[{
"name": "foo",
"place": "Paris",
"other": {
"var1": "asdf",
"var2": "asdf",
"var3": "sdfw",
etc....
}
},{
"name": "Bar",
"place": "Paris",
"other": {
"var1": "asdf",
"var2": "asdf",
etc....
}
}]
I need to have the data displayed as follows:
[{
"name": "foo",
"place": "Paris",
"var1": "asdf",
"var2": "asdf",
"var3": "sdfw",
etc...
},{
"name": "Bar",
"place": "Paris",
"var1": "asdf",
"var2": "asdf",
etc....
}]
So I want the object Other to be removed but keep al the values inside. What is the best way to achieve this. I can use Python3 or mongo aggregations.
Upvotes: 1
Views: 132
Reputation: 77912
Doing it in Python is technically possible and rather simple:
for obj in collection:
obj.update(obj.pop("other"))
but it should be faster to leave it to mongodb as explained in Anthony Winzlet's answer.
Upvotes: 2
Reputation: 46481
You can use below aggregation
using $replaceRoot
and $mergeObjects
db.collection.aggregate([
{ "$replaceRoot": {
"newRoot": { "$mergeObjects": ["$other", "$$ROOT"] }
}},
{ "$project": { "other": 0 }}
])
Upvotes: 4