- Reference >
mongo
Shell Methods >- Database Methods >
- db.addUser()
db.addUser()¶
On this page
Definition¶
-
db.
addUser
(document)¶ Use
db.addUser()
to add privilege documents to thesystem.users
collection in a database, which creates database credentials in MongoDB.Changed in version 2.4: The schema of
system.users
changed in 2.4 to accommodate a more sophisticated privilege model. In 2.4db.addUser()
supports both forms of privilege documents.In MongoDB 2.4 you must pass
db.addUser()
a document that contains a well-formedsystem.users
document. In MongoDB 2.2 pass arguments todb.addUser()
that describe user credentials. A 2.4 privilege document has a subset of the following fields:Field Type Description user
string The username for a new database user. roles
array An array of user roles. pwd
hash Optional. A shared secret used to authenticate the user. The pwd
field and theuserSource
field are mutually exclusive. The document cannot contain both.userSource
string Optional. The database that contains the credentials for the user. The userSource
field and thepwd
field are mutually exclusive. The document cannot contain both.otherDBRoles
document Optional. Roles this user has on other databases. Only valid for roles defined on the admin
database.See system.users Privilege Documents for documentation of the 2.4 privilege documents.
Examples¶
The following are prototype db.addUser()
operations:
This operation creates a system.users
document with a password using the
pwd
field
In the following prototype, rather than specify a password
directly, you can delegated the credential to another database
using the userSource
field:
To create and add a 2.4-style privilege document to
system.users
to grant
readWrite
privileges to a user named “author” with
privileges, use the following operation:
If you want to store user credentials in a single users
database, you can use delegated credentials, as in the following example:
Legacy Privilege Documents¶
To create legacy (2.2. and earlier) privilege documents,
db.addUser()
accepts the following parameters:
Parameter | Type | Description |
---|---|---|
user |
string | The username. |
password |
string | The corresponding password. |
readOnly |
boolean | Optional. Defaults to false . Grants users a restricted privilege set that
only allows the user to read the this database. |
The command takes the following form:
Example
To create and add a legacy (2.2. and earlier) privilege document with
a user named guest
and the password pass
that has only
readOnly
privileges, use the following operation:
Note
The mongo
shell excludes all
db.addUser()
operations from the saved history.
Deprecated since version 2.4: The roles
parameter replaces the readOnly
parameter for db.addUser()
. 2.4 also adds the
otherDBRoles
and
userSource
fields to documents in
the system.users
collection.