0

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 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.