Introduction:

Today we will setup a Single Instance of MongoDB Server on Ubuntu and will be using Ubuntu 16.04 for this tutorial.

What is MongoDB?

MongoDB is one of the NoSQL types of Databases, which is designed as shema-less design, which stores its data as JSON like documents and MongoDB is a distributed database which makes it easy to scale.

Some Definitions:

In MongoDB, we have databases, collections, documents and fields. A number of json documents are stored into a collection and a collection is part of a database.

Relational Databases such as MySQL is a lot different than NoSQL Databases, but we can kind-of compare the differences like the following:

-----------+------------+
|  MySQL   |  MongoDB   |
+----------+------------+
|  Table   | Collection |
|  Row     | Document   |
|  Column  |   Field    |
+----------+------------+

More into depth detail can be found here

Setting up the MongoDB Repoistory:

$ sudo apt update && sudo apt upgrade -y
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
$ sudo echo 'deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse' > /etc/apt/sources.list.d/mongodb-org-3.2.list
$ sudo apt update

After the repository has been setup, we can install mongodb.

Installing MongoDB Server:

$ sudo apt install mongodb-org -y

Config for SystemD:

Create the mongodb configuration file for systemd:

$ cat > /etc/systemd/system/mongodb.service << EOF
[Unit]
Description=MongoDB Server
After=network.target

[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target
EOF

Enable the service on startup:

$ sudo systemctl enable mongodb

Configuration for MongoDB:

By default the config should be basic enough for you to get the server started, but since we would like to enable clients from our subnet to connect to our server, we will change the bind-address from 127.0.0.1 to 0.0.0.0:

Below is the config that I used, you can head over to MongoDB Docs on Configuration for further fine-tuning:

$ cat /etc/mongod.conf
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 0.0.0.0

After your configuration is saved we can start the service.

Start MongoDB Server:

We can start the server like the following:

$ sudo systemctl start mongodb

Now that mongodb is started lets connect to mongodb and insert a document:

Insert a Document into MongoDB:

First connect to MongoDB:

$ mongo
MongoDB shell version: 3.2.12
connecting to: test
>

To see which database we are in:

> db
test

Create a Database mydb and insert a document into the mycollection collection, with the values of a Name, Surname, and Country:

> use mydb
switched to db mydb

> db.mycollection.insert({"name": "James", "surname": "John", "country": "South Africa"})
WriteResult({ "nInserted" : 1 })

> db.mycollection.find({})
{ "_id" : ObjectId("590a428485f8ab8ef90e16c2"), "name" : "James", "surname" : "John", "country" : "South Africa" }

From the last command we could see that the document was inserted into our database.

Enabling Authentication:

Since we allowed remote clients to connect to our mongodb instance its important to enable authentication on our mongodb instance.

We will first create the admin user, then update our configuration:

$ mongo
> use admin
> db.createUser({user: "dbadmin", pwd: "secretpass", roles:[{role: "root", db: "admin"}]})

Successfully added user: {
        "user" : "dbadmin",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}

Now lets update our config:

$ sudo vi /etc/mongod.conf

we are only appending the security section:

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 0.0.0.0

security:
  authorization: enabled

Restart our mongodb service:

$ sudo systemctl stop mongodb
$ sudo systemctl start mongodb

Now we should pass our authentication details to connect to our mongodb server:

$ mongo -u "dbadmin" -p "secretpass" --authenticationDatabase "admin"
MongoDB shell version: 3.2.13
> 

Now lets say we would like to grant the user James access to the database db01:

$ mongo -u "dbadmin" -p "secretpass" --authenticationDatabase "admin"
MongoDB shell version: 3.2.13
> use db01
switched to db db01
> db.createUser({user: "james", pwd: "pass", roles: ["readWrite"]})
Successfully added user: { "user" : "james", "roles" : [ "readWrite" ] }

$ mongo -u "james" -p "pass" --authenticationDatabase "db01"
MongoDB shell version: 3.2.13
connecting to: test
>

You will find, as we granted the user James access to the db db01 and due to the fact that it auto logged into test, we will not be allowed to list the dbs:

connecting to: test
> show dbs
  "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }"

We first need to switch to the db and then we can write to the database:

> use db01
switched to db db01
> db.test.insert({"foo": "bar"})
WriteResult({ "nInserted" : 1 })

I hope this was useful, please feel free to leave me a comment below, should you feel I had to add something to this post that might add value.