Update the DataType for a field inside the Nested Array

Hello Everyone, In the below mentioned document: I would like to update the tagSerialNumber to int64.

Please help me in updating the datatype

{
  "_id": {
    "$oid": "635286ea1c66064140400d67"
  },  
  "retailerRequestId": 82,  
  "receive": [
    {
      "receivedQty": 100,
      "receivedDate": "2015-12-01 18:16:46",
      "receivedStatus": {
        "statusId": 435,
        "status": "RReceivedFull"
      },
      "tagItems": [
        {
          "tagSerialNumber": "137438955172",
          "status": "RReceivedFull"
        },
        {
          "tagSerialNumber": "137438955171",
          "status": "RReceivedFull"
        },
        {
          "tagSerialNumber": "137438955170",
          "status": "RReceivedFull"
        },
        {
          "tagSerialNumber": "137438955169",
          "status": "RReceivedFull"
        },
        {
          "tagSerialNumber": "137438955168",
          "status": "RReceivedFull"
        }
      ]
    }
  ]
}

Hello @Amarendra_Krishna ,

You can use an update with aggregation pipeline starting from MongoDB 4.2,

  • $map to iterate loop of receive array
  • $mergeObjects to merge current object with updated property
  • $toLong to convert the type of tagSerialNumber to string
db.collection.updateMany(
  { "receive.tagItems.tagSerialNumber": { $type: "string" } },
  [{
    $set: {
      receive: {
        $map: {
          input: "$receive",
          in: {
            $mergeObjects: [
              "$$this",
              {
                tagItems: {
                  $map: {
                    input: "$$this.tagItems",
                    in: {
                      $mergeObjects: [
                        "$$this",
                        { tagSerialNumber: { $toLong: "$$this.tagSerialNumber" } }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }]
)

Playground

Warning: Should test in development environment first before production.

2 Likes

Thank you so much, this worked for me