Search code examples
mongodbmongoimport

mongoimport csv file that contains a column with array values


I am new to MongoDB and am trying to import a csv file containing programme data to MongoDB. One of the fields in the csv file (tags) contains a list of values as such:

enter image description here

When I import this into mongoDB, the entire field appears as a string:

"tags" : "[ethics.philosophy.plato]"

Is there any way that I can edit this field (either in the import command or manipulate the data in the database) such that the tag field is an array of values like this:

"tags" : ["ethics", "philosophy", "plato"]

I have looked online and through the mongoDB mongoimport documentation but have not found the relevant solution. Thanks in advance!


Solution

  • After CSV is imported, run this command.

    db.whatevercollection.find().snapshot().forEach(function (el) {
       el.tags = el.tags.split('.');  
     db.whatevercollection.save(el); 
    });
    

    Edit: Your CSV Contains Square Brackets.

        db.whatevercollection.find().snapshot().forEach(function (el) {
        el.tags=el.tags.substring(1,el.tags.length-1);     
        el.tags = el.tags.split('.');  
             db.whatevercollection.save(el); 
    });