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
You could
update
all your documents with a single pipeline.Try it on mongoplayground.net.
You may want to have a look at my answers in detail to a similar question below. Change int datatype to string in mongodb