Reshape all the documents in the collection

扶醉桌前 提交于 2019-12-30 10:39:37

问题


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.



来源:https://stackoverflow.com/questions/27580281/reshape-all-the-documents-in-the-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!