Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

CRUD Operations in MongoDB: Tutorial with Examples

Updated on 19 November, 2024

8.38K+ views
8 min read

With the continuous evolution of the web, we are now seeing how MongoDB and other document object databases are coming up as alternatives to conventional SQL based databases. There are several advantages that these document object databases have over SQL databases, and the most prominent ones out of all these benefits include scalability and agility.

It is important to note that data in MongoDB is stored binary encoded JSON (BSON) documents format. This format may have a requirement of holding arrays of embedded documents or for that matter values. A document forms a record in MongoDB, which is a structure created out of value and field pairs. 

Let us now discuss create, update, retrieve, and delete operations or CRUD operations in MongoDB. These functions can be broadly classified as data modification functions in MongoDB. These can only be used for a single collection. Insert is a function in MongoDB that can be used to add data to the database.

List of CRUD Operations in MongoDB

1. Creating Documents

How are objects created using MongoDB? MongoDB uses BSON – a binary representation of JSON – for its storage. So, it is quite easy to understand that methods used to perform different operations in the database have something or the other to do with JavaScript. Let us create a user and users’ collection. It is also important to note that tables in SQL are equivalent to collections in MongoDB.
db.users.save({name:”Mike”, job:”doctor”,email:”name@sample.com”})
This example uses MongoDB save() for saving the data to the collection.

2. Inserting Documents

  • Batch insert: This function allows for adding a list of documents at the same time to a database. A batch, at a particular point in time, can have hundreds or even thousands of documents. With the capability of inserting multiple documents, this function works a lot faster than other insert functions. A batch insert doesn’t need you to raise individual requests for the hundreds or thousands of documents. It instead works as one Transmission Control Protocol (TCP) request. The time taken during inserts is always significantly less as there is no header processing activity involved. Every document that has to be inserted carries a header that conveys to the database the operation that needs to be performed. Mostly, batch inserts are used to hold sensors data and server logs.
  • Mongoimport: Mongoimport is a command-line tool that is used in place of the batch insert to essential data from MySQL, Oracle, or any other Relational Database Management System (RDBMS). There are times when you may be required to make changes to documents – add a custom ID – before storing it on MongoDB. Another important thing that you should know is that MongoDB only accepts messages as heavy as 16 MB. So, the batch insert puts a restriction on the number of messages it can have. 
  •  Unordered bulk insert: In this function, MongoDB writes operations without following any order. In the event of an error taking place, it will continue with the write operations that are left without any interruption. MongoDB forms a group of the unordered operations while performing them. MongoDB can also seek performance enhancement by reordering listed operations before execution. So, applications don’t have to rely on a sequence when considering this function for bulk insert. Bulk.getOperations() can be used to see how MongoDB groups a set of operations and then executes them. This command can be used to add three documents at the same time but without any order.
  • Ordered bulk insert: In this function, MongoDB follows a sequence when writing operations. An error during any write operation results in MongoDB not performing other write operations. Ordered operations are grouped considering their continuity and type. Adjoining ordered operations belong to the same class are grouped.

For instance, if an ordered list has one insert operation followed by a delete operation followed by two update operations, MongoDB will create three groups to stack these. Group one will consist of one insert operation. The second group will have one delete operation. The third group will put the two update operations together.

The future editions of MongoDB are expected to deal appropriately with this behavior. Each group of ordered bulk lists can’t have more than 1000 operations. In case the number goes beyond that maximum limit, MongoDB creates smaller groups of 1000 operations or less, to adhere to this limit. So if there are 7000 ordered bulk operations, there will be seven groups, each consisting of 1000 bulk operations. To see how grouping and execution are done, first execute the bulk insert command and then use the Bulk.getOperations command. This command can be used to add three documents in order. 

3. Retrieving/reading Documents

Every query in MongoDB is directed at particular documents. MongoDB identifies documents based on the condition defined in a query and then returns those documents to its intended destination. A document retrieval query can have a projection that mentions conditions or criteria that match with the fields of the document that needs to be returned. 

Queries can be modified to put skips, limits and sort orders.

 Let us now discuss how the equality condition is specified. Use the findOne() command to identify a document’s first record. To display results in the proper format, you can use the pretty method. 

Use the db.items.find().pretty() query to identify all the documents listed in a collection and display all of them in a standardized format. You can use an empty query to pick all documents – db.items.find( {} ) – this query has an empty query clause at the end – so it will identify all documents listed in a collection. 

Not specifying the find method with a query document and using an empty query will both deliver the same result. So, db.items.find( {} ) and db.items.find() queries are equivalent in terms of the result they are used for. 

You can manipulate the query and use the query cursor method while the count method lets you find out the number of documents in a collection that match your query. db.items.count()

4. Updating Documents

You need to use the update() method to update documents in MongoDB. The update method features two important elements – query and update. Query parameter comes first followed by the update parameter. Here is an example

db.users.update({name:”Mike”}, {age: 32})

However, this isn’t the right way to update a value pair, which in this case is age. With this, you will overwrite everything in the document. The only thing that will remain in the age. So when we have to update a single value pair in the entire document, we need to use a few keywords. 

db.users.update({name: “Mike”}, { $set: { age: 28}})

This won’t overwrite anything. You would retain all the information the document has. Only the value of age will be updated. 

5. Removing Documents

Use the remove method – db.courses.remove() – to remove documents from a collection. This command will remove all the documents from the given collection. What it won’t remove are the indexes and the collection itself. At times, the remove command can take a query as a parameter. If you want to remove documents that match the criteria mentioned in the query, use db.items.remove({“item”: “Pen”) command. 

Use the db.items.remove({” item” : “Bag},1) command to remove only one document from a collection. To remove all the documents, collection, and indexes, use the db.courses.drop() command (drop method).

Conclusion

If you are interested to know more about Big Data, check out our Advanced Certificate Programme in Big Data from IIIT Bangalore.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Frequently Asked Questions (FAQs)

1. How are NoSQL databases better than conventional SQL-based databases?

The advantages of NoSQL databases become apparent when there is a large quantity of unstructured data. When you are not sure about the relationships within the data, such databases offer much greater flexibility. This is because, unlike SQL-based databases, which store data in relational tables, NoSQL databases are document-oriented. The structure is comparable to a file-folder arrangement, which allows them to assemble related information without necessarily categorizing it. NoSQL databases are also relatively easier to scale up, which means it is easy to increase the available storage by adding extra servers. This process is popularly referred to as “Sharding”.

2. How viable is a career in NoSQL technologies such as MongoDB?

As companies grow in size and further digitize their various processes, the demand for database developers to categorize and classify data has skyrocketed. Several companies have turned, or are planning to shift to NoSQL technologies for this. It is advisable to get a general grasp on the various technologies in this field instead of focusing exclusively on one. Hadoop, Cassandra, and Couchbase are some notable players. Salaries in this area are also quite generous, with developers making INR 4,15,000 per annum on average. However, depending on location, company, and experience, salaries may reach as high as INR 7,80,000 per annum.

3. What are the different types of NoSQL databases?

Based on their data models, NoSQL databases can be classified into several subtypes. The key-value store model is the least complex of these. It uses indexed key-value couples without employing any particular schema. Some examples are Azure and Cassandra. The column-store model, as its name suggests, stores data in columns instead of rows. This allows for higher scalability and faster performance. Then there is the Document database which enhances the key-value model, by giving each document its own designated key. It greatly simplifies storage, retrieval, and management. The graph model is capable of highly complex data representation. A lot of data is interconnected and represented as a graph.