在MongoDB中执行JavaScript文件
我想知道如何在MongoDB中执行JavaScript文件 这是我的JS文件中的一段简单代码:在MongoDB中执行JavaScript文件,javascript,mongodb,nosql,Javascript,Mongodb,Nosql,我想知道如何在MongoDB中执行JavaScript文件 这是我的JS文件中的一段简单代码: function loadNames() { print("name"); } 在命令提示符下,我试图像这样执行文件 mongo test.js 但它显示了错误: 意外标识符 有人能告诉我哪里出了问题吗?我通常这样运行测试查询,它也适用于您的示例代码 mongo < test.js mongo
function loadNames() {
print("name");
}
在命令提示符下,我试图像这样执行文件
mongo test.js
但它显示了错误:
意外标识符
有人能告诉我哪里出了问题吗?我通常这样运行测试查询,它也适用于您的示例代码
mongo < test.js
mongo
实现这一目标的两种方法:
一,。使用“--eval”
二,。执行js文件
mongo quickstats_db print.js
其中,print.js的内容是:
printjson(db.getCollectionNames())
从mongo--help
,我们得到:
$ mongo --help
MongoDB shell version v3.6.2
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
... ...
我们将这个脚本命名为my mongo script.js
:
'use strict';
// @see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";
var db = connect(MONGODB_URI);
var collections = db.getCollectionNames();
print(collections.join('\n'));
printjson(collections);
因此,这个cmdmongo--nodb my mongo script.js将执行脚本
您可以添加一个“-shell”,比如mongo--nodb--shell my mongo script.js
,以“在执行文件后运行shell”
'use strict';
// @see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";
var db = connect(MONGODB_URI);
var collections = db.getCollectionNames();
print(collections.join('\n'));
printjson(collections);