使用 mongo shell 更改 mongodb 中的文档结构
Change document structure in mongodb with the mongo shell
我在 mongodb 中有一个文档结构,我想为我的所有文档更改它而不使用像这样的聚合函数 response 但是通过创建一个特定的函数,并从中得到一个结果:
{
"_id" : ObjectId("String"),
"content" : {
"href" : "String",
"text" : "String",
"code" : "String "
}
}
到那个:
{
"_id" : ObjectId("String"),
"href" : "String",
"text" : "String",
"code" : "String "
}
请提出任何建议。谢谢。
最简单的方法是使用聚合框架。
然后将输出保存到 newCollection
中,验证后您可以删除旧的并重命名创建的。
db.collection.aggregate([{
$project : {
_id : 1,
href : "$content.href",
text : "$content.text",
code : "$content.code",
}
}, {
$out : "newCollection"
}
])
如果您不喜欢聚合(或者您的 content
的内容可能因文档而异),您也可以使用
db.coll.find().forEach(function (d) {
db.coll.update({
_id : d._id
}, {
$set : d.content,
$unset : {
'content' : 1
}
})
});
我在 mongodb 中有一个文档结构,我想为我的所有文档更改它而不使用像这样的聚合函数 response 但是通过创建一个特定的函数,并从中得到一个结果:
{
"_id" : ObjectId("String"),
"content" : {
"href" : "String",
"text" : "String",
"code" : "String "
}
}
到那个:
{
"_id" : ObjectId("String"),
"href" : "String",
"text" : "String",
"code" : "String "
}
请提出任何建议。谢谢。
最简单的方法是使用聚合框架。
然后将输出保存到 newCollection
中,验证后您可以删除旧的并重命名创建的。
db.collection.aggregate([{
$project : {
_id : 1,
href : "$content.href",
text : "$content.text",
code : "$content.code",
}
}, {
$out : "newCollection"
}
])
如果您不喜欢聚合(或者您的 content
的内容可能因文档而异),您也可以使用
db.coll.find().forEach(function (d) {
db.coll.update({
_id : d._id
}, {
$set : d.content,
$unset : {
'content' : 1
}
})
});