update datatype field int to decimal128 in mongo db in nested json structure



  • Hi have tried to updated nested field datatype

        db.test.find().forEach(function(data){
    data.age = NumberDecimal(data.age);
    data.phone.$.mob = NumberDecimal(data.phone.$.mob);
    db.test.updateOne({_id:data._id}, {$set:{age:data.age},{phone.$.mob:data.phone.$.mob}})
    })
    

    the above query I tried to run but not able to update data type

    Document Structure is

    {
    _id: (objectId)
    "lastname":"test",
    "age":25(int),
    "phone":[
    0:{
    "_id":(objectId),
    "mob":9000112 (int)
    },
    1:{
    "_id":(objectId),
    "mob":88909 (int)
    },
    2:{
    "_id":(objectId),
    "mob":88909 (int)
    }
    ]
    }
    

    Need to update every int field to decimal128 datatype thanks in advance



  • Try this one:

    db.collection.updateMany({},
       [
          {
             $set: {
                age: { $toDecimal: "$age" },
                phone: {
                   $map: {
                      input: "$phone",
                      in: { $mergeObjects: ["$$this", { mob: { $toDecimal: "$$this.mob" } }] }
                   }
                }
             }
          }
       ]
    )
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2