What is CRUD Operations in database? Any database program can perform only four possible operations. Create, Read, Update and Delete operations are together called CRUD Operations in database program - progrramers
Hello Programmers! In previous chapters we were introduced with MongoDB. Now we know that MongoDB is NoSQL database program that provides a mechanism for storage and retrieval of data in documents of tree structured collections and also we learnt ‘how to create/remove database and collections in MongoDB shell'.



Before we go ahead in this MongoDB Tutorial, let's take a tour on CRUD operation in any database.

What is CRUD Operations in database?

Any database program can perform only four possible operations as mentioned below :
  1. Create or Insert data/ documents in database
  2. Read or Select or Find data/documents from database
  3. Update data/document in database
  4. Delete data/document from database
Create, Read, Update and Delete operations are whole together called CRUD Operations in database program.
In this chapter of MongoDB Tutorial series we will see how to Insert, find, update and delete the documents in MongoDB shell.
So let’s go ahead and see how it is done. In previous post we have created database named ‘cricket’ and inside that database we have created a collection named ‘teamindia’. Now we go to perform CRUD Operations on that database through MongoDB Shell.

MongoDB : Create or insert Operation

Create or insert operations add new document to a collection. If the collection does not currently exist, insert operations will create the collection and add the document. Check the example for your reference

>db.teamindia.insertOne({
name:"Virat Kohali",
role:["Batsman", "Captain"],
batting:"Right-Hand Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


Above is the example of insert single document to a collection. In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
In other words, atomicity means "indivisibility" and "irreducibility”. MongoDB write operations are atomic, only at the level of a single document. If you're modifying multiple subdocuments inside a document the operation is still atomic, but if you're modifying multiple documents, the operation is not atomic.

>db.teamindia.insert({
name:"M.S.Dhoni",
role:["Wicketkeeper", "Batsman"],
batting:"Right-Hand Lower-Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


MongoDB shell provides following Methods to insert document in a collection :
  • db.collectionname.insert() – insert one or more document at same time
  • db.collectionname.inserOne() – insert one document at a time (Introduced in MongoDB 3.2)
  • db.collectionname.insertMany() – insert multiple document at a time (Introduced in MongoDB 3.2)

Mathod: db.collectionname.insert();

Using this method you can insert one or multiple document at a single write. It takes single data as a JavaScript object. MongoDB provides clients the ability to perform write operations in bulk. In this method, it takes array of JavaScript objects to insert multiple data at single write. Must check the below example carefully :
Example of db.collectionname.insert()

Mathod: db.collectionname.insertOne();

Using this method you can insert single document in a collections. It takes single data as a JavaScript object.
Example

Mathod: db.collectionname.insertMany();

Using this method you can insert one or multiple documents at a single write. Like db.collectionname.insert() method this (db.collectionname.insertMany()) method also takes array of JavaScript objects to insert multiple data at single write.


>db.teamindia.insertMany([
{
name:"Sikhar Dhawan",
role:["Batsman"],
batting:"Left-Hand Opener",
},
{
name:"Rohit Sharma",
role:["Batsman", "Vice Captain"],
batting:"Right-Hand Opener",
},
{
name:"Kedar Jadav",
role:["Allrounder","Batsman", "Bowler"],
batting:"Right-Hand Middle-Order",
bowling: "Right-Arm-Slinger-Off-Break"
},
{
name:"Rabindra Jadeja",
role:["Allrounder","Batsman", "Bowler"],
batting:"Left-Hand Lower-Middle-Order",
bowling: "Left-Arm-Off-Break"
},
{
name:"Jasprit Bumrah",
role:["Batsman", "Bowler"],
batting:"Right-Hand Talender",
bowling: "Right-Arm-Fast-Medium"
},
]);
>□


Check the above example carefully, Data in MongoDB has a flexible schema documents in the same collection. They do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.You can see in the above example.

With MongoDB, you may embed related data in a single structure or document. These schema are generally known as “denormalized” models, and take advantage of MongoDB’s rich documents. Embedded data models allow applications to store related pieces of information in the same database record.

Difference between db.collectionname.insert() and db.collectionname.insertMany() : progrramers explanation

The major difference between these two methods is the output response value after performing insert and insertmany operations. When inserting multiple document using insert method, you will get the response as BulkWriteResult() in JSON format (see in the below image) while inserting multiple document using insertMany you will get the acknowledge status as true/false and an array of ObjectId of inserted documents (see in the below image).

MongoDB Tutorial - difference between insert and insertMany
MongoDB Tutorial - difference between insert and insertMany


Note : The output response value is most important thing while you are working as professional. Professional programmers use the methods as per their requirement of output (return) values. Progrramers also suggest using the insert method as per requirement of response value.

MongoDB : Read or find Operation

Read or find operation retrieves the documents from collections.
MongoDB shell provides following Methods to query document in collections :
  • db.collectionname.find(); - find entire document(s) from a collection at a time
  • db.collectionname.findOne(); - find the single document from a collection (Introduced in MongoDB 3.2)

Mathod : db.collectionname.find();

Using this method you can retrieve the document in a collection and it returns a cursor of the selected documents. You can specify query criteria, projection and other filters to this method like motioned in below example :

>db.teamindia.find()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}

>□

While dealing with multiple output results, we can arrange

Method : db.collectionname.findOne();

Using this method you can retrieves the document as per query criteria and it returns a single document. If the criteria matches with multiple records it returns first document in collection according to the natural order which reflects the order of documents on the disk.

>db.teamindia.findOne()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}

>□


MongoDB : Update Operation

Using update operation you can modify existing document in a collection. MongoDB provides the following methods to update documents of a collection:
  • db.collection.update (); - Update document(s) in a collection
  • db.collection.updateOne(); - Update single document in a collection (Introduced in MongoDB 3.2)
  • db.collection.updateMany(); - Update multiple document in a collection (Introduced in MongoDB 3.2)
  • db.collection.replaceOne(); - Replace the entire content of a document except for the _id field (Introduced in MongoDB 3.2)

Method : db.collectionname.updateOne();

Using this method you can update single document in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the first matching document in the collection.

>db.teamindia.findOne({batting : "Left-Hand Opener"})
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.updateOne({"name" : "Sikhar Dhawan"},{$set:
{"batting" : "Right-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.teamindia.findOne({batting : "Left-Hand Opener"})
null
>□

Method : db.collectionname.updateMany();

Using this method you can update multiple documents in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the all matching document in the collection.

> db.teamindia.find({"batting" : "Right-Hand Opener"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Right-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}
> db.teamindia.updateMany({"batting" : "Right-Hand Opener"},{$set :
{"batting" : "Left-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
>□


Method : db.collectionname.replaceOne();

With this method your replace single document in a collection. It also takes multiple parameters as filter criteria like db.collectionname.updateOne(). When filter criteria matches with multiple document then it replaces the first matching document in the collection.

> db.teamindia.find({"name" : "Rohit Sharma"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.replaceOne({"name" : "Rohit Sharma"},{"name" : "Rohit Kohali",
"batting"
: "Right-Hand Opener","bowling":"Right-Arm Off Breack"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>□



Note : All above update methods take special Boolean parameter. If upsert : true then new document will added to collections if no match found with filter criteria or if match found then the existing document will be update.


MongoDB: Delete Operation

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection.
  • collection.remove(); - Removes single and multiple documents from a collection
  • collection.deleteOne(); - Removes single document form a collection (Introduced in MongoDB 3.2)
  • collection.deleteMany(); - Removes multiple or entire documents form a collection (Introduced in MongoDB 3.2)
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.

Method: db.collectionname.remove();

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

>db.teamindia.remove({"name" : "Rohit Sharma"});
WriteResult({ "nRemoved" : 1 })
>□


Removing Single Document from a collection

To remove a single document, call the remove() method with the justOne parameter set to true or 1.

Method: db.collectionname.deleteOne();

This method deletes the first document that matches the filter. You can use the unique index such as _id field for exact match.

>db.teamindia.deleteOne({"name" : "Kedar Jadav"});
WriteResult({ "nRemoved" : 1 })
>□

Method: db.collectionname.deleteMany();

This method deletes the entire documents that match the filter.

>db.teamindia.deleteMany({"batting" : "Right-Hand Talender"})
{ "acknowledged" : true, "deletedCount" : 3 }
>□

MongoDB Tutorial : How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations.
progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

1 comments:

  1. The final deliverable exemplified the original concept. The team was flexible, supportive, and accommodating.
    branding agencies in San Francisco

    ReplyDelete