Installing MongoDB 2.6 and Setting up Root User Login

mongoI 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.

  1. 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://keyserver.ubuntu.com:80 --recv 7F0CEB10
  2. Next create the list file for apt-get:
    <span class="nb">echo</span> <span class="s1">'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'</span> | sudo tee /etc/apt/sources.list.d/mongodb.list
  3. Then update your package database:
    sudo apt-get update
  4. And lastly, install MongoDB:
    sudo apt-get install mongodb-org
  5. 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
  6. Once you’re in the shell, switch to the database named admin like so:
    use admin
  7. 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"}]})
  8. 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:
    exit
  9. Now open the file /etc/mongodb.conf using your favorite editor and uncomment the line:
    #auth = true

    by removing the # character.

  10. Save the file and restart MongoDB:
    sudo service mongod restart
  11. 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.

Bookmark the permalink.

Comments are closed