MongoDB - 将简单字段更改为对象

标签 mongodb mongodb-query mongo-shell

在 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/

相关文章:

mongodb - 查找mongodb中所有未读对话

mongodb - 无法在 mongodb 中搜索 "once"

mongodb - 如何在 mongo shell 中运行本地脚本 - 解决方案 load()

mongodb - mongoS容器内的mongo连接错误

mongodb - 如何在 MongoDB 中按楼层聚合

node.js - 以下代码中的 db.createCollection 是否总是会设置一个新数据库?

javascript - mongodb中的快速分页如何显示上一页

mongodb - 向mongodb中的1亿条记录添加一个新字段

MongoDB 按键值对聚合/分组

java - Spring Data Mongo - 如何通过@DBRef 字段的 id 进行查询