MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.

Installation - Atlas Cloud

We can use this for free and its better then local server, as its more realistic environment. Go to http://www.mongodb.com and sign up for free cluster.

  1. Create new cluster
  2. Under Security -> Database Access create new user with Read and write to any database. You will need user and password later in your script where you will connect to db.
  3. Under Security -> Network Access add your current IP address.
  4. Back to Clusters, click on Connect, choose Connect your application


    Now install MongoDb driver npm install --save mongodb.

util/database.js

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const url = 'mongodb+srv://USER:PASSWORD@cluster0-gconm.mongodb.net/test?retryWrites=true&w=majority';

let _db;

const mongoConnect = (callback) => {
    MongoClient.connect(
        url
    )
        .then(client => {
            console.log('Connected !');
            _db = client.db();
            callback();
        })
        .catch(err => {
            console.log(err);
        });
}

const getDb = () => {
    if (_db) {
        return _db;
    }
    throw 'No database found !';
}
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;



app.js

...
const mongoConnect = require('./util/database');
const app = express();
...
mongoConnect(() => {
    console.log(client);
    app.listen(3000);
});




Installation - Local Server

This was tested on xubuntu 18.04.

Remove previous MongoDB installations

sudo apt remove --autoremove mongodb-o
sudo rm /etc/apt/sources.list.d/mongodb*.list
sudo apt update



Import the MongoDB public key

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4



Create mongodb-org-4.0.list file for Ubuntu 18.04 (Bionic)

echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list



Reload local package database

sudo apt-get update



Install MongoDB packages

sudo apt-get install -y mongodb-org



Install specific release of MongoDB

sudo apt-get install -y mongodb-org=4.0.6 mongodb-org-server=4.0.6 mongodb-org-shell=4.0.6 mongodb-org-mongos=4.0.6 mongodb-org-tools=4.0.6



Configure and Connect MongoDB

Create new admin user

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



Connect with new admin user

mongo -u admin -p password --authenticationDatabase admin



Examples

Show databases

show dbs;



Create new database

use DB_NAME;
use customer;



Create new collection

db.createCollection("users");



Show collections

show collections;



Inser new record

db.users.insert([{ first_name: "ferko", last_name: "mrkvicka", email: "ferko@gmail.com"}]);



Show all records

db.users.find();