Mongo 的 cli 告诉你自己如何用一个 js 文件来使用它
$ mongo --help
MongoDB shell version: 2.0.3
usage: mongo [options] [db address] [file names (ending in .js)]
...
用法:mongo [选项] [数据库地址] [文件名(以.js结尾)]
例如:
$ echo 'db.addUser("guest", "passwordForGuest", true);' > file.js
$ mongo mydb file.js
MongoDB shell version: 2.0.3
connecting to: mydb
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }
{
"user" : "guest",
"readOnly" : true,
"pwd" : "b90ba46d452e5b5ecec64cb64ac5fd90",
"_id" : ObjectId("4fbea2b013aacb728754fe10")
}
更新:
db.addUser 自 2.6 起已弃用
https://docs.mongodb.com/v2.6/reference/method/db.addUser/
改用db.createUser
:
// file.js
db.createUser(
{
user: "guest",
pwd: "passwordForGuest",
roles: [ { role: "read", db: "mydb" } ]
}
)
$ mongo mydb file.js