0

I'm writing a mongo shell script that will delete some entries in an existing DB, and then reload entries with data from a CSV (which was originally a spreadsheet file).

I'm at the point where I need to read the CSV file to make the entries to be inserted into the collection, but I can't figure how to read the CSV file while only using the js script. I know there are solutions (like this one) that shows how to use javascript with jquery to read the csv file, but I'm only using a js shell script file so those solutions aren't working for me.

This is what my mongo shell script looks like as of now:

printjson("Start");

// I will be deleting all entries, but for now only one.
printjson("Deleting Tag");
db.Tag.deleteOne({ name: "Tag Name" });

// Here is where I want to add entries from CSV into Mongo Colletion
// For now, I'm just inserting 1 with hard-coded data
printjson("Inserting Tag");
db.Tag.insertOne({
  name: "Tag name",
  description: "A tag used for testing",
});

// To verfiy the object was inserted
printjson("\nFinding Inserted Tag");
cursor = db.Tag.find({ name: "Tag name" });
while (cursor.hasNext()) {
  printjson(cursor.next());
}

printjson("End.");

And I run it in my terminal with a command like this:

mongo mongodb://{{mycreds}}@{{address of existing mongo}}:27017/{{DB I want}}?authSource=admin script.js

How do I read a csv file in a js shell script?

What I really want is to insert the data in the csv file into my mongo collection. If there's a better way than reading the file, creating entries from data, and then inserting, I'd love to know. Thank you for any assistance.

ineedtoknow
  • 1,283
  • 5
  • 28
  • 46
  • 1
    There is a `mongoimport` command-line tool using which you can import CSV data into a MongoDB collection. [mongoimport](https://docs.mongodb.com/manual/reference/program/mongoimport/index.html) is part of your MongoDB installation. – prasad_ Apr 24 '20 at 02:53
  • Yes thanks, I read up on that as well, but I doesn't say how to use it in a script. I'm not using the terminal/command line, I'm making a mongo shell script. (js) – ineedtoknow Apr 24 '20 at 12:38

0 Answers0