Home > OS >  How update string to number field
How update string to number field

Time:05-04

/* 1 */
{
    "_id" : ObjectId("62622dd73905f04f59db2971"),
    "array1" : [ 
        {
            "_id" : "21",
            "array2" : [ 
                {
                    "_id" : "123",
                    "answeredBy" : [ 
                        "success"
                    ]
                }, 
                {
                    "_id" : "124",
                    "answeredBy" : []
                }
            ]
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("626230e03905f04f59db29f5"),
    "array1" : [ 
        {
            "_id" : "22",
            "array2" : [ 
                {
                    "_id" : "223",
                    "answeredBy" : []
                }, 
                {
                    "_id" : "220",
                    "answeredBy" : []
                }
            ]
        }
    ]
}

How to convert "_id" : "21", and "_id" : "22", to "_id" : 21, and "_id" : 22,

CodePudding user response:

Here's one way to do it.

db.collection.update({
  "array1._id": { "$exists": true }
},
[
  {
    "$set": {
      "array1": {
        "$map": {
          "input": "$array1",
          "as": "elem",
          "in": {
            "$mergeObjects": [
              "$$elem",
              { "_id": { "$toInt": "$$elem._id" } }
            ]
          }
        }
      }
    }
  }
],
{
  "multi": true
})

Try it on mongoplayground.net.

  • Related