Mongo DB: Installation
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.
- Create new cluster
- Under
Security -> Database Accesscreate new user withRead and write to any database. You will needuserandpasswordlater in your script where you will connect to db. - Under
Security -> Network Accessadd your current IP address. - Back to
Clusters, click onConnect, chooseConnect your application
Now install MongoDb drivernpm 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 updateImport the MongoDB public key
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4Create 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.listReload local package database
sudo apt-get updateInstall MongoDB packages
sudo apt-get install -y mongodb-orgInstall 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.6Configure 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 adminExamples
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();