Once you have created a user administrator, you can use that account to create other user accounts that can administer, read, and write to the databases. You add user accounts by using the addUser()
method inside the MongoDB shell. The addUser()
method accepts a document
object that allows you to specify the user name, roles, and passwords that apply to that user. Table 12.2 lists the fields you can specify in the document
object.
MongoDB provides a number of roles that you can assign to a user account. These roles enable you to implement intricate privileges and restrictions on user accounts. Table 12.3 lists some of the most common roles that can be assigned to users.
readAnyDatabase
, readWriteAnyDatabase
, dbAdminAnyDatabase
, and userAdminAnyDatabase
can only be applied to users in the admin
database because they must apply to all databases.
To create a user, you should switch to that database and then use the addUser()
method to create the user object. The following MongoDB shell command illustrates creating a basic administrator user to the test
database:
use test
db.addUser( { user: "testUser",
pwd: "test",
roles: [ "readWrite", "dbAdmin" ] } )
Now here’s a more complex example that uses the otherDBRoles
to add a user to multiple databases. Keep in mind that you can only use otherDBRoles
on the admin
database. The following commands add the same user to the admin
database with only read
rights and give them readWrite
privileges to the testDB2
database:
use admin
db.addUser( { user: "testUser",
userSource: "test",
roles: [ "read" ],
otherDBRoles: { testDB2: [ "readWrite" ] } } )