问题
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