Installing MongoDB 2.6 and Setting up Root User Login

By Petr Kout, May 06, 2014

Installing MongoDB 2.6 and Setting up Root User Login

I recently started using MongoDB and I was struggling setting up the equivalent of a root user and other users in traditional SQL databases. MongoDB comes with authentication turned off out of the box, so in order to use the password challenge authentication, we have to create the root user followed by enabling the authentication. In this tutorial, we will cover that as well as installing MongoDB on Ubuntu.

  • First, let’s install MongoDB. The best way to go about it is to add the package source to your aptitude source list and installing using apt-get. Add the MongoDB public GPG key first:

    sudo apt-key adv --keyserver hkp:// --recv 7F0CEB10
  • Next create the list file for apt-get:

    <span class="nb">echo</span><span class="s1">'deb dist 10gen'</span> | sudo tee /etc/apt/sources.list.d/mongodb.list
  • Then update your package database:

    sudo apt-get update
  • And lastly, install MongoDB:

    sudo apt-get install mongodb-org
  • Now that the database engine is installed, we can go ahead and setup the root user. At this point, authentication is turned off, so you an log into the MongoDB shell simply by issuing:

    sudo mongo
  • Once you’re in the shell, switch to the database named admin like so:

    use admin
  • Next, create your root user by issuing this command in the shell. We will name the user admin and grant the user the root role:

    db.createUser({user:"admin", pwd:"secret_password", roles:[{role:"root", db:"admin"}]})
  • Now your admin user having the root role is created. MongoDB doesn’t have the exact same concept of the root user present in SQL databases. Instead, you can create as many users and assign them the root role, which will give them all privileges. You can exit the database shell:

  • Now open the file /etc/mongodb.conf using your favorite editor and uncomment the line:

    #auth = true

    by removing the # character.

  • Save the file and restart MongoDB:

    sudo service mongod restart
  • Finally, you can now log into the admin database like so:

    mongo -u admin -p secret_password --authenticationDatabase admin

    If you don’t provide the username and password and just issue the command `mongo` like before, you will be logged in, but with no privileges for any actions on the databases.