Skip to main content

MongoDB Setup & Overview



MongoDB is an open source, document oriented NoSQL database where data is represented & stored in the form of BSON(binary JSON) ” 

Following is a key value representation of data in JSON format and its corresponding BSON.It adds some "extra" information to documents, like length of string and sub-objects. This makes traversal faster.

// JSON file
   { "hello" : "world" }

// BSON file
"\x16\x00\x00\x00\x02hello\x00
\x06\x00\x00\x00world\x00\x00"


 
  \x16\x00\x00\x00                   // total document size
  \x02                               // 0x02 = type String
  hello\x00                          // field name
  \x06\x00\x00\x00world\x00          // field value
  \x00                               // 0x00 = type end of object 
 
With the growing use of Social Media platforms, large chunks of unstructured data was created .Thus, a need to to persist this unstructured data in the most efficient way possible hence NoSQL databases came into existence.
Following is a brief comparison between them,


SQL
No-SQL
  • Relational
  • Table
  • Predefined Schema
  • Vertically scalable
  • Better for transactions
  • Hierarchical
  • Document
  • Dynamic or No Schema
  • Horizontally scalable
  • Faster I/O

When between faster I/O and disk-space the choice is faster computation time, irrespective of the fact that we are duplicating the data then we must go for MongoDB


RDBMS
Mongo
  • Table,View
  • Row
  • Index
  • Join
  • Foreign Key
  • Partition
  • Collection
  • Document
  • Index
  • Embedded
  • Reference
  • Shard

Installation on Ubuntu

Inorder to install mongoDB on ubuntu, make sure you have a stable version(here 16.4) of Ubuntu & root privileges to the current ubuntu user & Follow the steps
  1. On the terminal screen, run following command to import MongoDB keys to your server.
    mCreate a MongoDB list file in /etc/apt/sources.list.d/ with this command,
  2. echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-o
    rg/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
  1. Update the repository with apt command
    sudo apt-get update
  2. Install MongoDB
    sudo apt-get install -y mongodb-org
  1. Create file ‘mongodb.service’
    sudo nano /lib/systemd/system/mongodb.service
and copy the file contents as follows
[Unit]
Description=MongoDB Database Service
Wants=network.target
After=network.target

[Service]
ExecStart=/usr/bin/mongod --config /etc/mongod.conf
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
User=mongodb
Group=mongodb
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target
Save the file and exit.

  1. Now update the systemd service with command below,
    systemctl daemon-reload
       create db folder at /data
cd /
sudo mkdir data
cd /data
sudo mkdir db

To start mongoDB service
sudo service mongod start
 
      Start service at boot time
      systemctl start mongod
      systemctl enable mongod

  1. Start MongoDB without access control. 
    mongod --port 27017 --dbpath /data/db
        on another terminal, Connect to the instance.
        mongo --port 27017

Basic Operations
  • To create database
> use testdb
switched to db testdb

  • To list all databases
> show dbs
testdb 0.000GB

  • To create a collection
> db.createCollection(“company”)
{ "ok" : 1 }

  • To list all collections
> show collections
company
  • To insert a document
> db.company.insert({empName:'aaa',empNo:101})
WriteResult({ "nInserted" : 1 })

  • To display the document
> db.company.find();
{ "_id" : ObjectId("5923e409848dfe0c013c5977"), "empName" : "aaa", "empNo" : 101 }
> db.company.find().pretty();
{
"_id" : ObjectId("5923e409848dfe0c013c5977"),
"empName" : "aaa",
"empNo" : 101
}
>


Comments

Popular posts from this blog

Redis Basic CRUD

We have seen how to setup on your linux machine here , now we will see how to perform basic CRUD operations using Spring Data & Redis server We will be creating a simple application that would persist an employee information into redis database. You will be needing certain JARs like jedis.jar, spring-data-redis.jar etc details of which you can download and view at https://github.com/meta-magic/RedisCRUDexample.git  First of all we will be creating the Employee entity, plz note that we are using the Serializable interface which automatically mapps the objects against the key. Employee.java import java.io.Serializable ; public class Employee implements Serializable { private static final long serialVersionUID = - 8243145429438016231L ; public enum Gender { Male , Female } private String id; private String name; private Gender gender; private int age; public String getId () { return id; } public void setId ( Str...

Ribbon , Hysterix using Spring Feign

The idea about this post is show some concept of  Load Balancing  & Circuit Breaker  using Spring Cloud Netflix API. Load Balancing Load Balancing automatically distributes incoming application traffic between number of nodes running for given application. Ribbon  : This provide client side load balancing. Its component offers a good set of configuration options such as connection timeouts, retries, retry algorithm  etc. Strategies offered by ribbon are listed below: Simple Round Robin LB Weighted Response Time LB Zone Aware Round Robin LB Random LB Circuit Breaker pattern Netflix’s Hystrix library provides an implementation of the Circuit Breaker pattern: when we apply a circuit breaker to a method, Hystrix watches for failing calls to that method, and if failures build up to a threshold, Hystrix opens the circuit so that subsequent calls automatically fail. While the circuit is open, Hystrix redirects calls to the metho...

CRUD in MongoDB & Spring Data

Now, since we have already been introduced to mongo and its server is setup. We shall now move on to performing basic CRUD operations. Lets take a use case example of ‘Company’ database that stores employee information.  We wish to store employee name, email address, age and multiple addresses. Traditionally in RDBMS we would create an Employee table and Address Table having foreign key reference to ‘employee id ‘ Incase of NoSQL, we will be creating Employee documnet which will have store employee information like name, email, age and an array of employes address. Following is a snippet of the schema defined { "name" : "", "email" : "", "age" : “”, "address" : [ ... ] } Thus to begin with, we will first define the entities. We have employee as an aggregate root entity that stores list of address having 1-M relatioship. Address Entity is represend as @Embeddable as it is embaded in another aggregate root entity. Employee is...