Change document structure in mongodb with the mongo shell [duplicate]

▼魔方 西西 提交于 2019-12-11 12:43:20

问题


I have a document structure in mongodb and i want to change it for all my documents without using aggregate function like this response but by creating a specific function, and have a result from that :

{
"_id" : ObjectId("String"),
"content" : {
    "href" : "String",
    "text" : "String",
    "code" : "String "
}
}

to that :

{
"_id" : ObjectId("String"),
"href" : "String",
"text" : "String",
"code" : "String "
}

Any suggestions please. Thank you.


回答1:


If you do not fancy aggregation (or your content's content may differ across documents) you can also use

 db.coll.find().forEach(function (d) {
    db.coll.update({
        _id : d._id
    }, {
        $set : d.content,
        $unset : {
            'content' : 1
        }
    })
});



回答2:


The easiets way to do it is to use aggregation framework. Then save output into newCollection and after verification you can delete old one and rename created one.

db.collection.aggregate([{
            $project : {
                _id : 1,    
                href : "$content.href",
                text : "$content.text",
                code : "$content.code",    
            }
        }, {
            $out : "newCollection"
        }
    ])


来源:https://stackoverflow.com/questions/37486849/change-document-structure-in-mongodb-with-the-mongo-shell

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