Learn MongoDB In A Nutshell

The following topics will be covered in this article,
  • Insert Document
  • Update Data in collection
  • Delete Data in collection
  • Get All collections from Database
  • Use Equal, Less than, Greater Than, Less than or Equal and Greater than or Equal operators
  • And Clause, Or clause, Not clause, Between clause and Like clause
  • Sort, Limit, Projection, Sum, Count, Min, Max, Avg, Date time, Join, Group By and Having Clause
Databases originated in the 1960s in order to replace the existing file organization of data.
 
The first databases that appeared used hierarchical (tree-like) or network structures to store data.
 

Types of Databases

 
SQL
 
Structured Query Language is the standard language for dealing with Relational Databases. In this, data uses schemas and relations and will be scaled vertically.
Important characteristics of the Databases,
  • Structured data
  • Related data
  • Metadata
  • Data integrity & Data security
  • Data storage, retrieval, and update
NoSQL
 
Not only is SQL a schema-less database for no-relations (very few) data maintenance, it’s possible to do horizontal and vertical data scaling. It stores and processes huge volumes of data.
 
Important characteristics of the NoSQL Databases,
  • Need to store unstructured data
  • Need for scalability and flexibility
  • Need for real-time access.
  • Types of NoSQL Databases:
The following main types of NoSQL databases can be identified, depending on the data model used:
  • Key-value store
  • Document store
  • Column-oriented
  • Graph-oriented
The characteristics of the most popular products from each category are taken into account when performing the analysis. These are,
  1. Redis for key-value stores;
  2. MongoDB for document stores;
  3. Apache Cassandra for column-oriented stores;
  4. Neo4j for graph-oriented stores.
MongoDB is a No SQL database. It is an open-source, cross-platform, document-oriented database written in C++.
 

Why Use Mongo DB

 
Please look into the below snapshot for better understanding,
 
Learn MongoDB In A Nutshell
 
We can interact with MongoDB in different ways, as listed below.
  • Use mongo shell to insert data and perform query operations.
  • Use MongoDB Compass to connect to insert data and perform query operations.
Here is the link for more details.
  • Here is the list of most popular third party MongoDB tools
MongoBooster – RoboMongo – MongoVUE – RockMongo – MongoHub -UMongo-3T Mongo Chef
 

Configuration through Mongo Shell

 
If you use “mongo” in the command prompt without configuring it, then it would give an error. Hence, configure it first.
 
Step 1
 
Go to the local disk C and get into Program Files. There you'll find a folder named MongoDB.
 
Learn MongoDB In A Nutshell
 
C:\Program Files\MongoDB\Server\3.2\bin\
 
Learn MongoDB In A Nutshell
 
Open Command prompts and type “mongod” to start the service.
 
Learn MongoDB In A Nutshell
 
MongoDB requires a data directory to store all data. Mongo DB’s default data directory path is \data\db.
 
Create this folder,
 
Learn MongoDB In A Nutshell
 
Write command on the command prompt “mongo” to create the connection.
 
Learn MongoDB In A Nutshell
 
MongoDB – Create Database
 
Creation of a database is so easy. All you have to do is to put “use” before the name of the database and press Enter.
 
First Create Connection,
 
Learn MongoDB In A Nutshell
 

Mongo list collections with the command “Show dbs”

 
Learn MongoDB In A Nutshell
 
As we have created a database, now, let's create a mongo collection in it. For this purpose, a user must insert certain records which make up a mongo document in collection i.e. via Field Names & Field Values.
 
Connect to a MongoDB instance running on your local host with default port 27017.
 
Create a database with the name is MovieDatabase. This database has 2 collections: Movie collection and Product collection. Movie collection and Region collection have a One to Many. One movie can have many products and one region belongs to one and only one category.
  1. /* Create MovieDatabase database */    
  2. use MovieDatabase     
Learn MongoDB In A Nutshell
  1. /* Create Movie collection */    
  2. db.createCollection('Movie');    
  3.     
  4. /* Dumping data for ` movie ` collection */    
  5. db.getCollection('movie').insert({    
  6.     name: 'Hollywood'    
  7. })    
  8.     
  9. db.getCollection('movie').insert({    
  10.     name: 'Bollywood'    
  11. })    
  12.     
  13. db.getCollection('movie').insert({    
  14.     name: 'Tollywood'    
  15. })    
  16.     
  17. WriteResult({ "nInserted" : 1 })    
  18.     
  19. > db.movie.find()    
  20.    { "_id" : ObjectId("5d6e06066f480eca73e15f22"), "name" : "Hollywood" }    
  21.    { "_id" : ObjectId("5d6e06106f480eca73e15f23"), "name" : "Bollywood" }    
  22.    { "_id" : ObjectId("5d6e061b6f480eca73e15f24"), "name" : "Tollywood" }    
  23. >   
Learn MongoDB In A Nutshell
  1. db.movie.find().pretty()   
Learn MongoDB In A Nutshell
  1. /* Create Region collection */  
  2. db.createCollection('region');  
  3.   
  4. /* Dumping data for `` collection */  
  5. db.getCollection('region').insert({  
  6.    FileName: 'Sahoo',  
  7.    Budget: '350',  
  8.    Language: 'Telugu',  
  9.    date: ISODate('2019-08-30'),  
  10.    movieId: ObjectId('5d6e061b6f480eca73e15f24'),  
  11.    Industry: {  
  12.       _id: new ObjectId(),  
  13.       name: 'Tollywood'  
  14.    }  
  15. });  
  16. db.getCollection('region').insert({  
  17.    FileName: 'Bahuballi',  
  18.    Budget: '200cr',  
  19.    Language: 'Hindi',  
  20.    date: ISODate('2015-08-30'),  
  21.    movieId: ObjectId("5d6e06106f480eca73e15f23"),  
  22.    Industry: {  
  23.       _id: new ObjectId(),  
  24.       name: 'Bollywood'  
  25.       }  
  26.    });  
  27.   
  28. db.region.find().pretty()  
Learn MongoDB In A Nutshell
 
Update Data in collection,
  1. db.getCollection('region').update(  
  2. {_id: ObjectId('5d6e11aa6f480eca73e15f2a')},  
  3. {  
  4.    $set:{Budget : '5000cr'}}  
  5. );  
Learn MongoDB In A Nutshell
 
Check now if collection is updated or not
  1. db.region.find().pretty()  
Learn MongoDB In A Nutshell
 
Delete Data in Collection
  1. db.getCollection('region').remove({_id: ObjectId('5d6e11aa6f480eca73e15f2a')});  
Learn MongoDB In A Nutshell
 
Check now if particular id collection is deleted or not,
 
Learn MongoDB In A Nutshell 
 

Get All collections from Database

 
Add some movies to the collections for better understanding.
  1. db.getCollection('region').find({})  
Use find() method to display documents in Region Collection
 
Learn MongoDB In A Nutshell 
 
Use Equal Operator in Query Commands
  1. db.getCollection('region').find({Language: 'Hindi'})  
Learn MongoDB In A Nutshell 
 
Use Less Than Operator in Query Commands
  1. db.getCollection('region').find({ Budget: { $lte: 500 } })  
Output
 
Learn MongoDB In A Nutshell 
 
Use Less Than or Equal operator in Query Commands
  1. db.getCollection('region').find({ Budget: { $lte: 500 } })  
Output
 
Learn MongoDB In A Nutshell 
 
Use Greater Than operator in Query Commands
  1. db.getCollection('region').find({ Budget: { $gt: 300} })  
Output
 
Learn MongoDB In A Nutshell 
 
Use Greater Than or Equal Operator in Query Commands
  1. db.getCollection('region').find({ Budget: { $gte: 300 } })  
Output
 
Learn MongoDB In A Nutshell 
 
And Clause in Query Commands
  1. db.getCollection('region').find({ $and: [{Budget: {$lt: 200}}, {Language: "English"}] }).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Or Clause in Query Commands
  1. db.getCollection('region').find({ $or: [{Budget: {$gt: 2200}}, {Language: "Telugu"}] }).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Not Clause in Query Commands
  1. db.getCollection('region').find({ Language: { $ne: "Hindi" } }).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Between Clause in Query Commands
  1. db.getCollection('region').find({ $and: [{Budget: {$gte: 100}}, { Budget: {$lte: 300}}] }).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 

Like Clause in Query Commands

 
Start with Mob string
  1. db.getCollection('region').find({FileName: /^Ti/}).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Ends with 2 string
  1. db.getCollection('region').find({FileName: { $regex: /hi$/ } } ).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 

Limit in Query Commands

 
If we want to fetch the first two documents from the collection "region", the following mongodb command can be used
  1. db.region.find().limit(2).pretty();  
If we want to fetch two documents after the first two documents from the collection 'region', the following mongodb command can be used :
  1. db.region.find().skip(2).pretty();  
If we want to fetch the two documents after the first document from the collection 'region', the following mongodb command can be used :
  1. >db.region.find().skip(1).limit(2).pretty();  
Output
 
Learn MongoDB In A Nutshell 
 
Sort by Budget Ascending
  1. db.getCollection('region').find().sort({Budget: 1})  
Output
 
Learn MongoDB In A Nutshell 
 
Sort by Budget Descending
  1. db.region.find().sort({Budget:-1}).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Sort and Condition
  1. db.getCollection('region').find({Language: "Hindi"}).sort({price: -1})  
Output
 
Learn MongoDB In A Nutshell 
 

Sum in Query Commands

 
Sum Budget
  1. db.getCollection('region').aggregate( [ { $group: { _id: '', total: { $sum: "$Budget" } } } ] ).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Sum Budget With Conditions
  1. db.getCollection('region').aggregate([  
  2.     {  
  3.         $match: {  
  4.             $and: [{Budget: {$lt: 200}}, {Language: "English"}]  }  
  5.     },  
  6.     {  
  7.         $group: { _id: '', total: { $sum: "$Budget" } }  
  8.     }  
  9. ]).pretty()  
Learn MongoDB In A Nutshell 
 
Count Product in Query Command
  1. db.getCollection('region').count()  
Output
 
Learn MongoDB In A Nutshell 
 
Sum Budget With Conditions
  1. db.getCollection('region').find({Budget: {$lt: 200}}).count()  
Output
 
Learn MongoDB In A Nutshell 
 

Min and Max in Query Commands

 
The Biggest Price
  1. db.getCollection('region').aggregate( [ { $group: { _id: '', total: { $max: "$Budget" } } } ] )  
Output
 
Learn MongoDB In A Nutshell 
 
The Smallest Budget
  1. db.getCollection('region').aggregate( [ { $group: { _id: '', total: { $min: "$Budget" } } } ] )  
Output
 
Learn MongoDB In A Nutshell 
 
Use Date and Time with Conditions
  1. db.getCollection('region').aggregate(  
  2.   {  
  3.       $project: { FileName: 1, Language: 1, month: {$month: '$date'}, year: {$year: '$date'}, day: {$dayOfMonth: '$date'} }  
  4.   },  
  5.   {  
  6.       $match: {month: 8, year: 2019}  
  7.   }  
  8. ).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Filter Data with Embed Document in Query Commands,
  1. db.getCollection('region').find({'Industry.name''Tollywood'}).pretty()   
Output
 
Learn MongoDB In A Nutshell 
 
Join and Conditions in Query Commands
  1. db.getCollection('region').aggregate(  
  2.     {  
  3.       "$match": { "Language"'Hindi' }  
  4.     },  
  5.     {  
  6.         "$sort": { "price": -1 }  
  7.     },  
  8.     {  
  9.         "$limit": 3  
  10.     },  
  11.     {  
  12.         $lookup: {  
  13.           "localField""_Id",  
  14.           "from""movie",  
  15.           "foreignField""_id",  
  16.           "as""IndustryInfo"  
  17.         }  
  18.     }, {  
  19.         $project: {  
  20.             'id': 1,  
  21.             'FileName': 1,  
  22.             'Budget': 1,  
  23.             'industry._id': 1,  
  24.             'industry.name': 1  
  25.         }  
  26.     }).pretty()  
Output
 
Learn MongoDB In A Nutshell 
 
Group By and Having in Query Commands
  1. db.getCollection('region').aggregate([  
  2.     {  
  3.         "$group" : {_id: "$Language",  
  4.             countProduct: {$sum: 1},  
  5.             sumQuantity: {$sum: '$Budget'},  
  6.          }  
  7.     },  
  8.     {  
  9.         $match: { sumQuantity: { $gt: 200 } } // Having  
  10.     },  
  11.     {  
  12.         $sort: { "sumQuantity": 1 }  
  13.     }  
  14. ]).pretty()  
Output
 
Learn MongoDB In A Nutshell 

MongoDB Compass GUI

 
MongoDB Compass to connect to insert data and perform query operations. Once we have downloaded and opened MongoDB Compass, we need to fill the below details for connecting mongo DB host. Here, at the top right corner, we have connection and disconnection options for connecting host. 
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell 
 
You can create a database from this UI.
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell 
 
Here you can create collections (tables).
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell 
 
Here point to the environments pipeline,
 
Learn MongoDB In A Nutshell
 
Learn MongoDB In A Nutshell 


Similar Articles