Change all documents in the collection
I have the following structure in my docs:
{
"_id" : 1,
"item" : {
"name" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-03-01T08:00:00Z")
}
}
And I want to convert each document:
{
"_id" : 1,
"name" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-03-01T08:00:00Z")
}
In other words, remove the embedded document, but not the details!
Thank!
+3
source to share
1 answer
You can use aggregation
especially $project
for this. The operator $out
allows you to write the result to another collection.
db.collection.aggregate([
{ "$project": {
"_id": "$_id",
"name": "$item.name",
"price": "$item.price",
"quantity": "$item.quantity",
"date": "$item.date"}
},
{ "$out": "collection"}
])
Your documents now look like this:
{
"_id" : 1,
"name" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-03-01T08:00:00Z")
}
You can also overwrite an existing collection by providing a new result collection with the same name, but this.
+5
source to share