MongoDB 's CRUD Operations

MongoDB 's CRUD Operations

Welcome to the world of DATABASES, In Databases there are mainly 2 categories

  • SQL ( Structured Query Language)

  • No SQL (Non-Structural Query Language)

In this blog, our main focus is on the No SQL language. And one of the No SQL databases is MongoDB so let's start

What is MongoDB and Why it even exists??

Before diving deep into CRUD operation on MongoDB first we have to find out why mongoDB even exists when we have mature Databases like MySQL

MongoDBMySQL
MongoDB is a document-based non-relational database management system. It’s also called an object-based system. It was designed to supplant the MySQL structure as an easier way to work with data.MySQL is a table-based system (or open-source relational database). The table-based design is the data query structure for search and is considered an SQL database. Also, data is searchable and accessible in relation to another data point or set.
Founded in 2007, MongoDB Inc. was a new approach to database design.SQL stands for “structured query language.” Developed in 1995, the MySQL database has become a default database structure and widely adopted as a result.

In Short, MongoDB is easy to use, manipulate, update data in comparison with SQL databases

How MongoDB Stored Data ??

Databases, collections, and documents are an important part of MongoDB without them you are not able to store data on MongoDB. A Database contains a collection and a collection contains documents and the documents contain data, that are related to each other.

In MongoDB, a database contains collections of documents. One Can create multiple databases on the MongoDB server

Document Structure in MongoDB is composed of field-and-value pairs and has the following structure:

{
    field1 : value1,
    field2 : value2,
    field3 : ["value1", "value2"]
}

CRUD

CRUD refers to CREATE, READ, UPDATE and DELETE. These terms describe the four essential operations for creating and managing persistent data elements, mainly in relational and NoSQL databases

Create

Create is as the name suggests "creating a new database or a new collection".

  • For creating a new database
use <database_name>

use blog_post

This above command creates new database name blog_post

  • For creating a new collection

    Create or insert operations and add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.

    MongoDB provides the following methods to insert documents into a collection:

db.collection.insertOne()

insertOne( ) is used when you have to insert only one document

// SYNTEX 
db.<collection_name>.insertOne({
    field1 : value1,
    field2 : value2,
    field3 : ["value1", "value2"]
})

// EXAMPLE 
db.user.inserOne({
    name : "Nikhil",
    no_of_blogs : 3,
    hobbies : ["playing_chess", "reading_manga"]
})

db.collection.insertMany()

insertMany( ) is used when you have to insert more than one document by only one command

//SYNTEX
db.products.insertMany([
<document>,
<document_1>,
<document_3>,
...n
])

//EXAMPLE 
db.products.insertMany([
{ _id: 1, item: "pencil", qty: 40 , price: 10 },
{ _id: 2, item: "pen" , qty: 50 , price: 30 },
{ _id: 3, item: "sharpner", qty: 50 , price: 10 }
])

In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

Read

Read operations retrieve documents from a collection i.e. query a collection for documents. MongoDB provides the following methods to read documents from a collection

You can specify query filters or criteria that identify the documents to return.

  • db.collection.find()

      //SUNTEX
      db.<colection_name>.find(
      { <query_criteria> }
      ).cursor_modifier 
    
      //EXAMPLE
      db.products.find() // fetch all the data with that collection
    
      db.products.find(
      { price : {$gt: 20 }}
      ).limit(2)
    
      // this gives the item whose price is more than 20 and only forst 2         item will be returned.
    

To know more about Query Operator( $gt , $lt ) Follow This Link

Update

Update operations are used to modify existing documents in a collection.

In MongoDB, update operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations.

MongoDB provides the following methods to update documents of a collection

  • db.collection.updateOne()

      // SYNTEX
      db.collection.updateOne(
         <filter>,
         <update>,
      )
    
      // EXAMPLE 
      db.products.updateOne(
      { _id : 2 }, // find document where _id = 2
      { $set: { price: 25 } } // and update price value to 25
      )
    
  • db.collection.updateMany()

      // SYNTEX
      db.collection.updateMany(
         <filter>,
         <update>,
      )
    
      // EXAMPLE 
      db.products.updateOne(
      { name : "nikhil" }, // find all document where name = "nikhil" 
      { $set: { std: 4 } } // and update their standard to 4 
      )
    
  • db.collection.replaceOne()

      // SYNTEX
      db.collection.replaceOne(
         <filter>,
         <replacement>,
      )
    

Delete

Delete operations remove documents from a collection or a whole database.

In MongoDB, delete operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.

MongoDB provides the following methods to delete documents from a collection:

  • db.dropDatabase()

    To delete the whole Database

      // MAKE SURE YOU ARE ONE THAT DATABASE 
      // THEN 
      db.dropDatabases()
    
  • db.collection.deleteOne()

      // SYNTEX
      db.collection.deleteOne(
         <filter>
      )
    
      // EXAMPLE 
      db.products.deleteMany({_id : 1 }) 
      // IN THIS CASE AS A FILTER ALWAYS USE ID TO DELETE THE DOCUMENT
    
  • db.collection.deleteMany()

      // SYNTEX
      db.collection.deleteMany(
         <filter>
      )
    
      // EXAMPLE 
      db.products.deleteMany({name : "nikhil"})
      // ANY DOCUMENT THAT MATCHES THIS QUERY WILL BE DELETED (ALL OF THEM)
    

So this is it for this blog post , i hope you enjoyed reading through it

thanks for reading , feedback appriciated