How to write and execute mongoDB scripts

There are times when we need to save the steps or commands of mongo shell and need to get it executed in the same order (for reusability and automation and avoid errors). The best solution is to save it in a file with any extension preferred is js, however I call it as mjs which means mongo javascript. With below command you can run it in bash

aseem278$ mongo < /Users/asee2278scripts/mongoScript.mjs

TIP : To be effective while writing query, you write commands using IDE to use auto complete, formatting, Json format verification and then redirect input to mongo 

Sample mongoScript.mjs

use school

db.scores.drop()

var types = [‘exam’, ‘homework’, ‘quiz’]

for (student_id = 0; student_id < 100; student_id++) {

    for (type=0; type < 3; type++) {

   var r = {‘student_id’:student_id, ‘type’:types[type], ‘score’:Math.random() * 100};

   db.scores.insert(r);

    }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s