- Reference >
mongoShell Methods >- Database Methods >
- db.addUser()
db.addUser()¶
On this page
Definition¶
-
db.addUser(document)¶ Use
db.addUser()to add privilege documents to thesystem.userscollection in a database, which creates database credentials in MongoDB.Changed in version 2.4: The schema of
system.userschanged 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.usersdocument. 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 userstring The username for a new database user. rolesarray An array of user roles. pwdhash Optional. A shared secret used to authenticate the user. The pwdfield and theuserSourcefield are mutually exclusive. The document cannot contain both.userSourcestring Optional. The database that contains the credentials for the user. The userSourcefield and thepwdfield are mutually exclusive. The document cannot contain both.otherDBRolesdocument Optional. Roles this user has on other databases. Only valid for roles defined on the admindatabase.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.