A Quick Tour of MongoDB

what are we going to learn -

  • what is MongoDB(definition)

  • Why is it used(some advantages and features)

  • How to use it (Installation and commands)

  • Which products perform what tasks(MongoDB Compass, MONGOSH, MongoDB Atlas)

What is MongoDB ??

MongoDB is a document-based database known for its flexibility and scalability, it stores data in the form of document which looks similar to JSON objects.

Why do we need MongoDB ??

It is a non-relational database that is used to store data in structured or unstructured manner making it easy and convenient for the developers.

Some advantages of MongoDB are ->

  • Document Model - in Relational DB we use a tabular format to store the data whereas in MongoDB collections are made in which there are one or multiple documents that consist of fields.

  • Deployment Options - While using MongoDB Atlas we can deploy our database using the cloud where service providers like AWS, Azure, etc are in partnership with MongoDB and you can use it for free.

  • Large Community Support - We all know while facing any errors, or issues community support is the savior for all those problem facers, and so does MongoDB. Anyone can refer to their official documentation as well as other platforms too.

Comparison with Relational DB

In SQL, DATABASE>TABLE>{ ROW, COLUMN }

In MongoDB, DATABASE>COLLECTION>DOCUMENT(are like js objects and here document resembles rows)>FIELD

Installation

Simply search "download MongoDB" in your browser and install the MSI version from the community server. After downloading simply keep clicking next and click on "Complete installation" Also don't forget to check the box "install MongoDB Compass" it will reduce your work by automatically downloading it.

Note: It is the procedure of installation for Windows. For Mac, it is a bit different

mongodb://[username:password@]host1[:port1][,...hostN[.. is a URI String with the help of which we can connect to our MongoDB, it can be with/without password

mongodb://localhost:27017 - ByDefault it is the URI String

Basic Commands

After you are done with the installation and exploration of MongoDB, now we should know some of the basic commands in MongoDB

  1. returns all databases present in our MongoDB --

        show dbs
    
  2. connecting/accessing the database --

     use database_name
    
  3. (CRUD operations) Create --

     db.collection_name.insertOne( 
         { name: "Souvik",
          roll: "21CS011148" ,
          sub: ["phy", "chem", "maths"] ,
          struct: { h:178, w: 68 } 
         } 
     )
    

    for inserting many documents at a time just make arr of obj and use insertMany()

  4. (CRUD operations) Read --

     db.collection_name.find()    => fetch all docs
     ------------
     db.Students.find( { roll:"21CS011148" } )    => fetch roll 48
     ------------
     db.Students.find( { sub: { $in: [ "phy" , "P" ] } } )    => fetch from matching the element in arr
     ------------
     db.inventory.find( { status: "A", qty: { $lt: 30 } } )     => it is AND operation (means both true will give true)  ($lt means less than)
     ------------
     db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )    => it is OR operation (means either one will give true)
     ------------
     db.Students.findOne( { sub: { $in: [ "phy" , "P" ] } } )    => fetch from matching the element in arr and gives only document(means 1 item)
    
  5. (CRUD operations) Update --

     db.inventory.updateOne(
         { item: "paper" },
         {
           $set: {"size.uom":"cm", status: "P" },
           $currentDate: { lastModified:true }
         }
     )    => it will replace in with cm & status D with P & change the date
     ----------------
     db.inventory.updateMany(
        { "qty": { $lt: 50 } },
        {
          $set: { "size.uom": "in", status: "P" },
          $currentDate: { lastModified: true }
        }
     )    => it will update multiple records as per condition
     ----------------
     db.inventory.replaceOne(
        { item: "paper" },
        { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
     )    => it will replace item with instocks
    
  6. (CRUD operations) Delete --

     db.inventory.deleteOne({ status : "A" })    => will delete the 1st document satisfying the cond
     ----------------
     db.inventory.deleteMany({ status : "A" })    => will delete the all documents satisfying the cond
     ----------------
     db.inventory.deleteMany({})    => will delete all the documents
     ----------------
     db.inventory.remove({})    => will delete all the documents
    

    deleteManay() returns boolean value where as remove() returns the document deleted

  7. Sorting and some more queries --

db.inventory.find().sort( {qty:1} )    => sort in ascending order on the basis of qty
----------------
db.inventory.find().sort( {qty:1} )    => sort in descending order on the basis of qty
----------------
db.inventory.find().limit(1)    => will give only 1 or as per the value
----------------
db.inventory.find().skip()    => will skip the 1st or n as per value (used for pagination)
Pagination example
for example - db.collection_name.find().skip((pageNo-1)no).limit(no) (1) for 1st page query will be=> db.coll_name.find().skip((0)8).limit(8) (2) for 2nd page query will be=> db.coll_name.find().skip(8).limit(8)

"pageNo" =>current page-number || "no" =>number of records to be shown || let no=8 (here)

MongoDB Compass

MongoDB Compass is a tool where we can access our database with proper visuals and it is the local database and we can perform whatever tasks we want.

In Windows, it can be installed while installing MongoDB but in Mac, we have to install it manually.

It is the home page from where you can make multiple clusters and login to it and access MongoDB

The rows are documents and each row inside the document(eg. _id, name) are fields.

MONGOSH

MONGOSH is the shell of MongoDB which is used to run query. We can manually perform CRUD operations but it would be very haptic. That's why a single query can make our work easy.

MongoDB Atlas

it is a cloud-based platform used to deploy your database on the cloud and access your database from the cloud.

Steps for using Atlas
Just google mongoDB atlas and create an account and then use shared db (because it's free) and choose the region and cloud service provider and you are good to go.

Aggregation pipeline

When the query is run, we want that query to run through a stage of process so that's why we use a pipeline and it can be reused in the future for pulling the data from the database.

db.orders.aggregate( [
   // Stage 1: it will select data acc to the match condition
   {
      $match: { size: "medium" }
   },
   // Stage 2: it will group the data acc to match cond and the group cond
   {
      $group: { _id: "$name", totalQuantity: { $sum: "$quantity" } }
   }
] )
// here name will be used as the id or we can say it will be the unique constraint

That is it for this blog. I hope you found it helpful and it was just an overview of MongoDB you can check out and practice more using MongoDB's official documentation MongoDB Documentation.