mongodbmongodb-querymongo-shell

MongoDB - change simple field into an object


In MongoDB, I want to change the structure of my documents from:

{
    discount: 10,
    discountType: "AMOUNT"
}

to:

{
    discount: {
        value: 10,
        type: "AMOUNT"
    }
}

so I tried following query in mongo shell:

db.discounts.update({},
    {
        $rename: {
             discount: "discount.value",
             discountType: "discount.type"
        }
    },
    {multi: true}
)

but it throws an error:

"writeError" : {
    "code" : 2,
    "errmsg" : "The source and target field for $rename must not be on the same path: discount: \"discount.value\""
}

A workaround that comes to my mind is to do it in 2 steps: first assign the new structure to a new field (let's say discount2) and then rename it to discount. But maybe there is a way to do it one step?


Solution

  • The simplest way is to do it in two steps as you allude to in your question; initially renaming discount to a temporary field name so that it can be reused in the second step:

    db.discounts.update({}, {$rename: {discount: 'temp'}}, {multi: true})
    db.discounts.update({}, 
        {$rename: {temp: 'discount.value', discountType: 'discount.type'}},
        {multi: true})