在 MongoDB 中,我想更改文档的结构:
{
discount: 10,
discountType: "AMOUNT"
}
到:
{
discount: {
value: 10,
type: "AMOUNT"
}
}
所以我尝试在 mongo shell 中执行以下查询:
db.discounts.update({},
{
$rename: {
discount: "discount.value",
discountType: "discount.type"
}
},
{multi: true}
)
但是它抛出一个错误:
"writeError" : {
"code" : 2,
"errmsg" : "The source and target field for $rename must not be on the same path: discount: \"discount.value\""
}
我想到的解决方法是分两步完成:首先将新结构分配给一个新字段(比如 discount2
),然后将其重命名为 discount
。但也许有一种方法可以一步到位?
最佳答案
最简单的方法是按照您在问题中提到的那样分两步完成;最初将 discount
重命名为临时字段名,以便在第二步中重复使用:
db.discounts.update({}, {$rename: {discount: 'temp'}}, {multi: true})
db.discounts.update({},
{$rename: {temp: 'discount.value', discountType: 'discount.type'}},
{multi: true})
关于MongoDB - 将简单字段更改为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34178232/