MongoDB running scripts from files

NOTE: This example uses MongoDB 3.2

Running scripts on MongoDB can be very time saving and save you the trouble of running the same commands on the shell everytime. This post will explain how to run your own scripts from files in MongoDB using a simple example. So first fire up your mongod:

The following query will return the documents from students collection having a class field of 2.

This query returns a cursor which the mongo shell automatically iterates for us and displays. Now, if we were to store this as a cursor and iterate over it, we can do something like this:

Here school is the database which needs to be specified if not included in your query.js file.

An alternative is to include the database itself in the query.js file using db.getSiblingDB(‘dbName’);

So, the new query.js file looks like:

The new query.js file can be run simply as:

You would have already guessed it but just to be sure, this query searches for students collection in school database and returns all the documents having a score greater than 65 and sorting it increasingly.

You may also like...