And*_*rei 26 mongodb mongo-shell
如何使用mongo shell执行外部文件并在控制台中查看结果?
我有外部文件,query.js我希望执行它并在cmd中查看结果.
比方说,该文件的内容是:
db.users.find()
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 41
把它放到你的query.js文件中:
function get_results (result) {
print(tojson(result));
}
db.col.find().forEach(get_results)
Run Code Online (Sandbox Code Playgroud)
并运行:
mongo db_name query.js
Run Code Online (Sandbox Code Playgroud)
这是一个很好的解释,为什么你应该这样做.
Nel*_*elu 15
我发现从文件运行mongodb查询并在控制台中查看输出的最简单方法是:
query.js:
use my_db;
db.my_collection.findOne()
Run Code Online (Sandbox Code Playgroud)
在命令行上:
mongo <query.js
这将显示控制台的所有输出,就像您单独在mongo shell中运行查询一样.
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)
Run Code Online (Sandbox Code Playgroud)
Command
mongo < test.js
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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().
| 归档时间: |
|
| 查看次数: |
37512 次 |
| 最近记录: |