I have a string field in a mongodb collection which holds values in comma separated string. Now i want change the type of that particular field to array. As the collection contains 30 million records, would the below query have any performance implications?
db.getCollection("collectionName").find().forEach( function (el) {
el.NameofFieldToChangeType = el.NameofFieldToChangeType.split(',');
db.databaseName.save(el);
});
Considering the amount of data, I would definitely run this directly on the server. Here is an example that works to use as a guide. It will replace the names field with a new array from the $split.
db.collectionName.aggregate(
[
{ "$addFields": {
"names": { "$split": [ "$names", "," ] }
}},
{$out:"collectionName"}
]
)
Before 4.2, you have to use aggregation with an $out stage to achieve what you need.
db.collectionName.aggregate(
[
{ "$addFields": {
"NameofFieldToChangeType": { "$split": [ "$NameofFieldToChangeType", "," ] }
}},
{$out:"collectionName"}
]
)
Starting with 4.2, you can use updateMany with aggregation in update param, like this :
db.collectionName.updateMany(
{},
[{$addFields:{"NameofFieldToChangeType": { "$split": [ "$NameofFieldToChangeType", "," ]}}
}]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With