Show/Hide Toolbars

MongoDB Notes

Navigation: MongoDB Authentication

Setting Up a Replica Set and User

Scroll Prev Top Next More


In this procedure, you will configure a replica set and set up a user with permissions to configure the members of the replica set.  This procedure is a prerequisite to configuring the various authentication configurations described in this section.  The procedure assumes that the database is created, not that there is an existing database that should be preserved.




1.Create three initial mongod configuration files.  (See example below.)  Note that authentication is not enabled.

2.Start each mongod instance with these commands, where initX.yaml is the configuration file for the Xth member of the replica set.


mongod -f init1.yaml

mongod -f init2.yaml

mongod -f init3.yaml


4.Using the mongo shell, log into the first member of the replica set.


mongo --port 31210 --host


5.Initiate the replica set with the appropriate server name and port.  


rs.initiate( {

   _id : "repl",

   members: [ { _id : 0, host : "" } ]



6.Create the user administrator using the localhost exception.


use admin

var user = {user: "userAdmin", pwd: "badges", roles: [{role: "root", db: "admin"}]}



7.Authenticate as userAdmin.


db.auth('userAdmin', 'badges')


8.Add additional members to the replica set.





9.Exit mongo with: exit.

10. Stop members of replica set with: killall mongod.


Example Initial Configuration File



  destination: file

  path:  /home/vagrant/data/r0/mongodb.log


  dbPath: /home/vagrant/data/r0 


  fork: true



  port: 31210


   replSetName: repl




Creating a user with root role violates the security principal of least privilege.  For production environments, once you have your servers configured, add users and roles that divide up responsibilities and deny privileges to users who do not need them.  (See Examples of Roles in MongoDB and LDAP.)  Once these users are working properly, delete the user with the root role.


Related Information


To view mongod processes that are running (in Linux), perform the following command:


ps -ef | grep mongod


To stop all mongod processes, perform the following command:


killall mongod


Use the rs.status() command to check the status of the replica set.