Reshape all the documents in the collection

2019-02-18 13:55发布

问题:

I have the following structure in my documents:

{
    "_id" : 1,
    "item" : {
        "name" : "abc",
        "price" : 10,
        "quantity" : 2,
        "date" : ISODate("2014-03-01T08:00:00Z")
    }
}

And I want to transform each document on this:

{
    "_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!

Thanks!

回答1:

You can use the aggregation especially the $projectoperator for that. The $out operator let you write the result in another collection.

db.collection.aggregate([
    { "$project": {
        "_id": "$_id", 
        "name": "$item.name",
        "price": "$item.price", 
        "quantity": "$item.quantity", 
        "date": "$item.date"}
    }, 
    { "$out": "collection"}
])

You documents now look like this:

{
    "_id" : 1,
    "name" : "abc",
    "price" : 10,
    "quantity" : 2,
    "date" : ISODate("2014-03-01T08:00:00Z")
}

You can also overwrite the pre-existing collection by giving the new results collection the same name but this.