MongoDB

MongoDB is one of the most popular document oriented databases which is a major type of NoSQL database.  The document oriented databases closely resemble RDBMS in the sense that the data is stored in form of documents (which are similar to rows in RDBMS) and the documents are stored in collections (which are similar to tables in RDBMS). The biggest difference with RDBMS is that the documents are indeed meant for storing semi structured data and also the documents are completely schema free. This means that in MongoDB you can go ahead and store documents in collections without even creating the collection in the first place.

This also means that MongoDb insert operations are much faster than corresponding insert operations of RDBMS.

Typical CRUD syntax in MongoDB

Following are the useful CRUD commands of MongoDB:

// First query below finds employees with title Gupta and second query finds employees who are managers
// Sql equivalent of the first query: Select * from employees where title = "Gupta"
// Sql equivalent of the second query: Select * from employees where designation = "Manager"
db.employees.find("title":"Gupta") 
db.employees.find("designation":"Manager")
 

// One can also select specific columns instead of all columns 
// Sql equivalent : Select name, age from employees where title = "Gupta"
db.employees.find("title":"Gupta" , {name: 1, age:1}) 

// One can also limit specific rows 
// Sql equivalent : Select name, age from employees where title = "Gupta" LIMIT 5
db.employees.find("title":"Gupta" , {name: 1, age:1}).limit(5) 

// One can also sort the output 
// Sql equivalent : Select * employees order by title ASC name DESC
db.employees.find.sort("title":"1" , "name" : "-1") 
// First one below is a single insert statement and the second one is a multi insert (batch insert)
db.employees.insert({name:"Soumik",age:"40", specialities: ["java", "NoSql", "AWS"], physique: {height:"170", weight:"70"} }) 
db.employees.insertMany([
{name:"Rahul",age:"34", specialities: ["java"], physique: {height:"170", weight:"70"} },
{name:"Agni",age:"30", specialities: ["NoSql"], physique: {height:"170", weight:"70"} },
{name:"Suny",age:"38", specialities: ["NoSql"], physique: {height:"170", weight:"70"} }
 ])
 
// Speciality of MongoDB is that it allows one to store the following data in a cell:
// a) Single value (just like RDBMS) , b) An array of values (within a [] bracket) like the 'specialities' column above , c) a nested structure 
// which is like the 'physique' column above
// Below is the MongoDB find statement which finds out all employees with height greater than 150
// See how a nested field 'physique' is referenced using the dot notation
db.employees.find({ "physique.height" : { $gt: 150 }}) 
 
// Update query which sets the age of employee named Soumik to make his age 41 
db.employees.update({name:"Soumik"},{$set: {age: "41"} }}) 

Some other useful/ interesting features and commands of MongoDB

You can indeed (as an exception) create a collection in MongoDB before you insert documents using the below commands:

// Creates a collection named 'log' which is capped/restricted to the fact that max documents can be either 5000 or max size 5242880 B 
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

//Creates a collection named 'contacts' in MongoDB which has the validations against specific fields
db.createCollection( "contacts",
   {
      validator: { $or:
         [
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }
         ]
      }
   }
)

BTW, mongo shell (which is the mongo client) accepts all javascript commands and hence you can wrap multiple MongoDB commands in a .js file and run it as below:

// Runs the file 'myjsfile.js' 
mongo localhost:27017/test myjsfile.js

// However if you are already within the mongo shell, you can just use the load function
mongo>>load(myjsFile.js)

MongoDB also supports various kinds of indexes and below are some examples (BTW MongoDB has now very strong support for text index, details of which are beyond the scope of this blog but I will try to write a blog on text and geo-spatial index of MongoDB )

//below command retrives all the existing indexes of a collection
db.<collectionName>.getIndexes()

//below command creates an index on the field named 'age'
db.<collectionName>.createIndex(age:1)

//below command creates a text index on the field named 'subject'
db.articles.createIndex( { subject: "text" } )

//below command leverages the text index to do text search of the word 'coffee' within the 'subject' column
db.articles.find( { $text: { $search: "coffee" } } )

MongoDB Replication & Sharding

One of the most attractive features of MongoDB is the ease with which one can divide and distribute the data into multiple nodes (known as sharding) and how each part of the data (known as shard) can be duplicated (known as replication).
Below are very simple steps to create a sharded cluster in MongoDB

This completes the setup of a sharded replica set of MongoDB.