Mongo shell execute query from file and show result

Andrei picture Andrei · May 1, 2013 · Viewed 45k times · Source

How to execute external file using mongo shell and see the result in console?

I have external file, like query.js and I would like to execute it and see the result in cmd.

Let's say, content of the file is:

db.users.find()

Answer

alecxe picture alecxe · May 1, 2013

Put this into your query.js file:

function get_results (result) {
    print(tojson(result));
}

db.col.find().forEach(get_results)

and run:

mongo db_name query.js

Here's a good explanation why you should do it this way.