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

Here is a more simple and elegant solution:

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

Tested with MongoDB 2.4.8


I know AD7six has already given an issue but when I try, I obtain a user with a database authentication 'test'.
So I added one command before create User to choose this authentication database.

db = db.getSiblingDB('myDataBase');
db.createUser(
 {
   user: "myUser",
   pwd: "myPwd",
   roles: [
    { role: "readWrite", db: "myDataBase" }
   ]
 }
);

The authentication database and the database used by the user can be different. The command "getSiblingDB(dataBase)" (Javascript) is an alternative to "use dataBase" (Shell)


Mongo's cli tells you itself how to use it with a 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 example:

$ 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 2.6
https://docs.mongodb.com/v2.6/reference/method/db.addUser/

use db.createUser instead:

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

$ mongo mydb file.js