为什么将复制粘贴到MongoDB shell中有效,但不能从* .js文件读取相同的代码?

时间:2018-07-18 08:27:06

标签: windows mongodb cmd

我得到了要粘贴到mongodb shell中的命令列表。通常,我以管理员身份打开cmd,将目录更改为MongoDB bin文件夹,启动mongo.exe,然后简单地执行复制粘贴操作。我的问题是如何编写正确的文件以打开mongo shell并直接发送命令列表?尝试将代码示例另存为test.js,但“ mongo.exe test.js”始终返回语法错误:意外标识符。仍然同时复制粘贴运行没有单个错误。

下面是完整的代码示例:

    use admin
db.dropUser("root");
db.dropUser("someuser");
db.dropUser("someadmin");
db.dropUser("someuser");
db.dropUser("someadmin");
db.createUser(
{
user: "root",
pwd: "pswd",
customData: { description: "default admin user" },
roles: [
"readWriteAnyDatabase",
"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"clusterAdmin"
]
}
);
use usersdb;
db.dropUser("someuser");
db.dropUser("someadmin");
db.dropUser("someuser");
db.dropUser("someadmin");
use maindb;
db.dropUser("somereader");
db.dropUser("someuser");
db.dropUser("someadmin");
db.dropUser("someuser");
db.dropUser("someadmin");
db.createUser(
{
user: "somereader",
pwd: "somereader",
customData: { description: "maindb read-only user" },
roles: [
"read"
]
}
);
db.createUser(
{
user: "someuser",
pwd: "30d1ef22ff41d9b031b6e1d80a3cbd695ea78835f821093f6f836bbe6107aa5b",
customData: { description: "maindb app user" },
roles: [
"readWrite",
{role: "read", db: "someusers"},
{role: "read", db: "admin"},
{role: "clusterAdmin", db: "admin"}
]
}
);
db.createUser(
{
user: "someadmin",
pwd: "eac55b089924b85e17a44070ed7cb0ebef74263786fccaf005f5955eafaae934",
customData: { description: "maindb admin user" },
roles: [
"readWrite",
"dbAdmin",
{role: "readWrite", db: "someusers"},
{role: "dbAdmin", db: "someusers"},
{role: "read", db: "admin"},
{role: "clusterAdmin", db: "admin"}
]
}
);

提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先,创建一个JavaScript文件来批量操作:

test.js
//#####################################
var count = db.foo.find().count()
print("Total count:"+count)

现在,在终端上:

mongo <db-name> test.js

Output:
MongoDB shell version v3.4.15
connecting to: mongodb://127.0.0.1:27017/foo
MongoDB server version: 3.4.15
Total count: 68

请注意,该脚本文件不支持use <database>,因此必须在mongo命令上提供名称。请参阅官方文档:https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/