Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a comma separated string field to array in mongodb

Tags:

mongodb

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);
    });
like image 264
Jaganmohanreddy Avatar asked Oct 29 '25 12:10

Jaganmohanreddy


2 Answers

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"}
    ]
)
like image 73
Samuel Goldenbaum Avatar answered Nov 01 '25 07:11

Samuel Goldenbaum


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", "," ]}}
  }]
)
like image 26
matthPen Avatar answered Nov 01 '25 08:11

matthPen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!