After creating the first user on admin
database (the user "ram", which you had created successfully) which can administrate users and roles (a user administrator), you need to do these following steps to create other users:
Shutdown the mongod
instance, from the mongo
shell:
use admin
db.shutdownServer();
Exit the shell.
Start the mongod
again with the auth
option:
The --auth
option enables authorization to control user's access to
database resources and operations. When authorization is enabled,
MongoDB requires all clients to authenticate themselves first in order
to determine the access for the client.
mongod --auth --port 27017 --dbpath ...
From now onward, clients that connect to this instance must authenticate themselves as a MongoDB user. The clients can only perform actions as determined by their assigned roles.
Connect to the instance from mongo
shell:
mongo --port 27017 --authenticationDatabase "admin" -u "ram" -p "rams_password"
Now you have authenticated yourself as a user administrator. So, you can create other users with various roles.
Create additional users as needed, now (for example):
use db2
db.createUser(
{
user: "db2User",
pwd: "db2_pass",
roles: [ { role: "readWrite", db: "db2" } ]
}
)
This will create a user "db2User" which has the role "readWrite" on the database "db2". Note the use db2
command before the createUser()
; it means that the authentication database for this user is "db2". When this user needs to read or write data to the "db2" database he/she needs to authenticate against this database, like this from mongo
shell:
mongo --port 27017 --authenticationDatabase "db2" -u "db2User" -p "db2_pass"
Note that, your authentication database can be different from that of the database you specify in the roles
, for example:
use db2
db.createUser(
{
user: "mongoUser",
pwd: "mongo_pass",
roles: [ { role: "read", db: "myDB" } ]
}
)
The Error:
The error you are getting is because that you have not authenticated yourself as a user administrator, before creating new users.
To understand this in detail, you need to get familiar with MongoDB Security aspects of Authentication and Authorization.