Update the DataType for a field inside the Nested Array

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