Mongo shell execute query from file and show result

人走茶凉 提交于 2019-12-03 04:28:59
alecxe

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.

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.

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!