4

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);
    });

2 Answers 2

6

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"}
    ]
)
Sign up to request clarification or add additional context in comments.

6 Comments

@matthPen this code has been tested and verified against v 4.0.4 before posting the example. Not sure why you feel this doesn't work.
db.databaseName.save(el); => never applied with your aggregation. You just transform data on query response, but never persists these data in db.
But you're right on the transformation itself, and about the amount of data.
You mean data is updated in your database after your aggregation query? In other words, if you performs your aggregation, you can do a find() after that and get array instead of string for "names" field? Curious to see that wihtout $out stage...
no problem, Everybody faced that kind of mistake at least once. :)
|
2

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", "," ]}}
  }]
)

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.