复制并重命名 MongoDB 中的文档字段
问题描述:
我想重命名我的 Mongo 集合中所有文档都有的字段.已经有一个很好的答案.但我不想覆盖当前的属性名称,而是想将重命名的属性保存为新字段,保持原始属性不变.
I want to rename a field that all documents have in my Mongo collection. There's already a great answer for that. But instead of overwriting the current property name, I want to save my renamed property as a new field, leaving the original intact.
想象一下我的文档是这样的:
Imagine my documents look like this:
{
"property": "Original property value"
}
我想得到这个:
{
"property": "Original property value",
"property_new": "Original property value"
}
我该怎么做?
答
您可以使用 $out
聚合
db.collection.find([
{ "$addFields": {
"property_new": "$property"
}},
{ "$out": "newCollection" }
])
它将创建一个名为 newCollection
的新集合,只需将其重命名为现有集合即可.
It will create a new collection with the name newCollection
just rename it with the existing one.