- Security >
- Security Tutorials >
- Access Control Tutorials >
- Add a User to a Database
Add a User to a Database¶
To add a user to a database you must authenticate to that database as a
user with the userAdmin
or userAdminAnyDatabase
role. If you have not first created a user with one of those roles, do
so as described in Create a User Administrator.
When adding a user to multiple databases, you must define the user for each database. See Password Hashing Insecurity for important security information.
To add a user, pass the db.addUser()
method a well formed
privilege document that contains the
user’s credentials and privileges. The db.addUser()
method
adds the document to the database’s system.users
collection.
Changed in version 2.4: In previous versions of MongoDB, you could change an existing user’s
password by calling db.addUser()
again with the user’s
username and their updated password. Anything specified in the
addUser()
method would override the existing information for
that user. In newer versions of MongoDB, this will result in a duplicate
key error.
To change a user’s password in version 2.4 or newer, see Change a User’s Password.
For the structure of a privilege document, see system.users
. For descriptions of user roles, see
User Privilege Roles in MongoDB.
Example
The following creates a user named Alice
in the
products
database and gives her readWrite
and
dbAdmin
privileges.
Example
The following creates a user named Bob
in the
admin
database. The privilege document
uses Bob’s credentials from the
products
database and assigns him userAdmin
privileges.
Example
The following creates a user named Carlos
in the
admin
database and gives him readWrite
access to the
config
database, which lets him change certain settings for
sharded clusters, such as to disable the balancer.
Only the admin
database supports the
otherDBRoles
field.