MongoDB | A Beginners Guide

Setup MongoDB in 10 minutes

Mayank Patel
6 min readMar 16, 2021

Let’s start by understanding what is a NoSQL database ?

  • NoSQL stands for “not only SQL” referring to non-relational databases.
  • Data is modeled in means other than tabular relations like in a document store or key-value pair or graphs.
  • NoSQL came into existence in the late 1960s but became popular in the 21st century.
  • NoSQL includes ease of scaling, simplicity of design & control over availability.

What issues does it solve ?

  • A NoSQL database being schema-less gives means to model data closer to its application.
  • A SQL database lacks the power to scale properly in a horizontal direction, while a NoSQL database was designed from the ground up to be distributive in nature.
  • Most NoSQL databases provide benefits of automatic sharding, replication & scaling.

MongoDB is a scalable, flexible NoSQL document database. MongoDB is well known for its horizontal scaling and load balancing capabilities, which provide an unprecedented level of flexibility and scalability.

How to Configure and access MongoDB ?

There are 3 ways in which you can setup and access MongoDB

  1. MongoDB Atlas.
  2. MongoDB on-premise (locally).
  3. MongoDB as a Docker Container.

Setting Up MongoDB Atlas

It is the easiest way to get hands-on with MongoDB with the provided free tier which gives 500MB of storage space. It’s useful when you are collaborating with others and need database access.

Steps:

  • Select the ‘‘Starter Cluster’’ and click on “Create a Cluster”.
  • Select a Cloud Provider & Region nearest to you.
  • Select M0 Sandbox for cluster tier and it’s free forever.
  • Provide a name to the cluster and press “Create Cluster

Next is to connect to your MongoDB cluster you just created.

  • Click on “Database Access” on the console.
  • Create a new database user with a username and password with admin privileges.
  • Click on “Network Access” on the console and click “ADD IP ADDRESS
  • Enter “0.0.0.0/0” for access entry list, which will allow access to your database from all IP addresses — ( not recommended in production builds ).
  • Go to your cluster and click on Connect, select the connection method, and copy the link provided. replace username and password with your admin credentials.
clicked on Connect your Application, here my username is already set to blackcat & language Node.js

Use this link to connect to your MongoDB Cluster

mongodb+srv://<username>:<password>@cluster0.5rkbg.mongodb.net/?retryWrites=true&w=majority

Setting Up MongoDB locally

Instead of wasting your bandwidth with cloud DB, you can directly setup mongo locally with unlimited space.

  • Navigate to this link and download the MongoDB community edition for your platform. — for Windows users.
  • On Installation add a new path for mongo and mongod in environment variables. — for Windows users.
Windows users can download the zip file and extract it
  • Ubuntu users can run sudo apt install mongodb
  • In the bin directory, you will find mongo and mongod executables.
  • mongod’ is a background process used by MongoDB, where as ‘mongo’ is a command-line interface (CLI).
  • First, start the server with sudo systemctl start mongodb and run the CLI with mongo .

Setting up MongoDB container

This is the easiest way to deploy scale and operate MongoDB.

First of all, you will have to install docker, Installation instructions are provided in this link.

  • Open the terminal after installation and run docker -v to check if installed properly.
  • run docker pull mongo , mongodb docker image will be downloaded.
  • run docker images and mongo image must be listed below
  • run docker run -it -d mongo this will build and deploy a container of image mongo in interactive and detached mode.
the container is running on port 27017
  • Connect with your database with url = mongodb://localhost:27017
  • Access mongo CLI with sudo docker exec -it <container name> mongo
Accessing mongo CLI in the docker container

Let’s run some commands mongo CLI

To connect to your mongoDB server :

  • MongoDB Atlas :

mongo “mongodb+srv://cluster0.5rkbg.mongodb.net” — username <username>

  • MongoDB Container : mongo mongodb://127.0.0.1:27017
//selecting the db to work on
> use example
switched to db example

//inserting anew document in collection users > db.users.insertOne({ id: 100, name: "mayank", message: "hello"} ) {
"acknowledged" : true, "insertedId" : ObjectId("604f2f3b957d7b6fee938c49") } //inserting multiple documents in users > db.users.insertMany([{ id: 101, name: "joe", message: "how you doin"}, { id: 102, name: "ross", message: "we were on a break"}] ) {"acknowledged" : true, "insertedIds" : [ ObjectId("604f2f8e957d7b6fee938c4a"), ObjectId("604f2f8e957d7b6fee938c4b")] } //listing all documents in users > db.users.find() { "_id" : ObjectId("604f2f3b957d7b6fee938c49"), "id" : 100, "name" : "mayank", "message" : "hello" } { "_id" : ObjectId("604f2f8e957d7b6fee938c4a"), "id" : 101, "name" : "joe", "message" : "how you doin" } { "_id" : ObjectId("604f2f8e957d7b6fee938c4b"), "id" : 102, "name" : "ross", "message" : "we were on a break" }

//listing all documents with id = 100 > db.users.find({id:100}) { "_id" : ObjectId("604f2f3b957d7b6fee938c49"), "id" : 100, "name" : "mayank", "message" : "hello" }

//updating document with id = 100, setting their message field to "world" > db.users.updateOne({id: 100}, {$set: {message: "world" }}) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.users.find({id:100}) { "_id" : ObjectId("604f2f3b957d7b6fee938c49"), "id" : 100, "name" : "mayank", "message" : "world" }
//removing all documents with id = 100 > db.users.remove({id:100}) WriteResult({ "nRemoved" : 1 })
> db.users.find() { "_id" : ObjectId("604f2f8e957d7b6fee938c4a"), "id" : 101, "name" : "joe", "message" : "how you doin ?" } { "_id" : ObjectId("604f2f8e957d7b6fee938c4b"), "id" : 102, "name" : "ross", "message" : "we were on a break" }

Connecting MongoDB server with Applications in Python and Node.js ?

Python and Node.js are very popular languages used for server-side scripting.

Node.js

  • Install mongodb driver from npm => npm install --save mongodb
  • import the mongodb package and call the connect function with the database url.
  • It returs a promise handle then and reject function properly.
var MongoClient = require('mongodb').MongoClientvar db = null
var mClient = null
//replace username and password with your credentials
const db_url = "mongodb+srv://<username>:<password>@cluster0-5rkbg.mongodb.net/test?retryWrites=true&w=majority"
MongoClient.connect(db_url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if(err) {
console.log(`error : ${err}`)
}else {
mClient = client
db = client.db("example")
if (db == null) {
console.log(`database inaccessible`)
}else {
console.log(`Database Connected !!`)
}
})

Python

  • install the pymongo library using pip => pip install pymongo
  • import pymongo and create a client Object of class MongoClient passing database url in parameter.
from pymongo import MongoClient#replace username and password with your credentials
db_url = "mongodb+srv://<username>:<password>@cluster0-5rkbg.mongodb.net/test?retryWrites=true&w=majority"
client = MongoClient(db_url)db = client['example']
collection = db['user']

--

--

Mayank Patel
Mayank Patel

Written by Mayank Patel

Android Dev.| Web Dev. | Freelancer | Portfolio : https://maaayank.github.io

No responses yet