Search code examples
mongodbmongo-shell

Mongo shell execute query from file and show result


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()

Solution

  • 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.