How can I use a script to create users in mongodb?

I am going to configure mongodb, and we use a puppet to control our server configuration.

I have most of the settings I need, but I need to create a user inside the mongo database.

I know how to do this using the mongo shell, and I know that I can do this using javascript / a.js using the command

db.addUser("username", "password"[, readOnly])

However, I could not find a convincing example of what needs to be done for javascript. Moreover, I need to be able to add a user from the command line using some kind of shell script.

If someone can

a) tell me some compelling examples of using javascript with mongoDB and

b) How to do this from the command line?

+5
source share
3 answers

Mongo cli tells you how to use it with js file

$ mongo --help
MongoDB shell version: 2.0.3
usage: mongo [options] [db address] [file names (ending in .js)]
...

usage: mongo [options] [db address] [file names (ending in .js)]

For instance:

$ 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")
}

Udpate:
db.addUser deprecated since version 2.6
https://docs.mongodb.com/v2.6/reference/method/db.addUser/

use db.createUserinstead:

// file.js
db.createUser(
  {
    user: "guest",
    pwd: "passwordForGuest",
    roles: [ { role: "read", db: "mydb" } ]
  }
)

$ mongo mydb file.js

+11
source

Here is a simpler and more elegant solution:

echo 'db.addUser("<username>", "<password>");' | mongo <database>

Tested with MongoDB 2.4.8

+2
source

http://www.mongodb.org/display/DOCS/Scripting+the+shell

or write a script using your favorite scripting language using the appropriate MongoDB language driver.

0
source

All Articles