skip to Main Content

I have an array like below for gc collection where I need to change datatype from int64 to string for CardNumber.This should be done for all records in this collection.I wrote the script as below but on executing there is no conversion happening.Any help would be appreciated.

    Eg: GiftCardSale[2 element]
       [0] GiftCardId 62e201874a555cb001d2d723
           CardNumber 5678967546738766 (Int64)
           Amount 20
       [1] GiftCardId 62e201874a555cb001d2d723
           CardNumber 6789879874673829  (Int64)
           Amount 10

    
db.gc
  .find(
    {
      GiftCardSale: {
        $elemMatch: {
          CardNumber: { $exists: true, $type: 18 },
        },
      },
    },
    {
      _id: 2,
    }
  )
  .forEach(function (doc) {
    db.gc.update(
      {
        _id: doc._id,
      },
      {
        $set: {
          'GiftCardSale.$[etl].CardNumber': {
            $toString: '$GiftCardSale.$[etl].CardNumber',
          },
        },
      },
      { arrayFilters: [{ 'etl.CardNumber': { $type: 18 } }], multi: true }
    );
  });

2

Answers


  1. You could update all your documents with a single pipeline.

    db.gc.update({
      "GiftCardSale.CardNumber": {"$type": "long"}
    },
    [
      {
        "$set": {
          "GiftCardSale": {
            "$map": {
              "input": "$GiftCardSale",
              "as": "sale",
              "in": {
                "$cond": [
                  {"$eq": [{"$type": "$$sale.CardNumber"}, "long"]},
                  {
                    "$mergeObjects": [
                      "$$sale",
                      {"GiftCardSale": {"$toString": "$$sale.CardNumber"}}
                    ]
                  },
                  "$$sale"
                ]
              }
            }
          }
        }
      }
    ],
    {
      "multi": true
    })
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
  2. You may want to have a look at my answers in detail to a similar question below. Change int datatype to string in mongodb

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search