Mongo shell execute query from file and show resul

2019-03-17 15:09发布

问题:

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

回答1:

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.



回答2:

The simplest way I found of running mongodb queries from a file and seeing the output in the console is this:

query.js:

use my_db;
db.my_collection.findOne()

On the command line: mongo <query.js

This displays all the output to the console, as if you were running the queries in the mongo shell individually.



回答3:

Good information here - wanted to point out that mongo provides a printjson() function so there is no need to write your own unless you need more functionality than printjson() provides.

Example Mongo file (test.js)

// Pretty print all documents in test.scratch
use test
db.scratch.find().forEach(printjson)

Command

mongo < test.js

If you want to omit use test from the mongo file, perhaps to remove IDE error indications for js files, you can specify the target db on the command line:

mongo test < test.js

Interesting to note: the above examples use a redirect to push the file into the mongo shell. This calling convention allows you to enter commands just as you would in the shell; including mongo shell convenience commands like use test.

Mongo provides another script calling convention: mongo test test.js which omits the redirect operator. This calling convention requires test.js to be proper javascript and cannot use the mongo shell convenience methods like use test; one would use the javascript equivalents like getSiblingDB().



回答4:

One thing other answers didn't mention is that use db command won't work in external script. The best way is to use getSiblingDB, for example, if I want to use database called my_db:

db = db.getSiblingDB("my_db");

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

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

Then everything works as you would expect. See Write Scripts for the mongo Shell.



回答5:

This seems to have changed at some point in the mongo cli, I had to execute the following command to get it to run a file against the database (with mongo cli version 3.4.9)

mongo mongodb://192.168.1.1/YourDataBase scriptFile.js

Then replace 192.168.1.1 with the ip / hostname of your db, YourDataBase with the database name and point to an existing file