Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconBig Databreadcumb forward arrow iconCRUD Operations in MongoDB: Tutorial with Examples

CRUD Operations in MongoDB: Tutorial with Examples

Last updated:
4th Feb, 2020
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
CRUD Operations in MongoDB: Tutorial with Examples

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.

Ads of upGrad blog

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. 

Explore our Popular Software Engineering Courses

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. 

In-Demand Software Development Skills

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. 

Ads of upGrad blog

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).

Explore Our Software Development Free Courses

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.

Profile

Kechit Goyal

Blog Author
Experienced Developer, Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech) focused in Computer Science from Indian Institute of Technology, Delhi.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Popular Big Data Course

Frequently Asked Questions (FAQs)

1How 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”.

2How 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.

3What 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.

Explore Free Courses

Suggested Blogs

Top 10 Hadoop Commands [With Usages]
11947
In this era, with huge chunks of data, it becomes essential to deal with them. The data springing from organizations with growing customers is way lar
Read More

by Rohit Sharma

12 Apr 2024

Characteristics of Big Data: Types & 5V’s
5758
Introduction The world around is changing rapidly, we live a data-driven age now. Data is everywhere, from your social media comments, posts, and lik
Read More

by Rohit Sharma

04 Mar 2024

50 Must Know Big Data Interview Questions and Answers 2024: For Freshers & Experienced
7315
Introduction The demand for potential candidates is increasing rapidly in the big data technologies field. There are plenty of opportunities in this
Read More

by Mohit Soni

What is Big Data – Characteristics, Types, Benefits & Examples
185822
Lately the term ‘Big Data’ has been under the limelight, but not many people know what is big data. Businesses, governmental institutions, HCPs (Healt
Read More

by Abhinav Rai

18 Feb 2024

Cassandra vs MongoDB: Difference Between Cassandra & MongoDB [2023]
5468
Introduction Cassandra and MongoDB are among the most famous NoSQL databases used by large to small enterprises and can be relied upon for scalabilit
Read More

by Rohit Sharma

31 Jan 2024

13 Ultimate Big Data Project Ideas & Topics for Beginners [2024]
100349
Big Data Project Ideas Big Data is an exciting subject. It helps you find patterns and results you wouldn’t have noticed otherwise. This skill
Read More

by upGrad

16 Jan 2024

Be A Big Data Analyst – Skills, Salary & Job Description
899712
In an era dominated by Big Data, one cannot imagine that the skill set and expertise of traditional Data Analysts are enough to handle the complexitie
Read More

by upGrad

16 Dec 2023

12 Exciting Hadoop Project Ideas & Topics For Beginners [2024]
20855
Hadoop Project Ideas & Topics Today, big data technologies power diverse sectors, from banking and finance, IT and telecommunication, to manufact
Read More

by Rohit Sharma

29 Nov 2023

Top 10 Exciting Data Engineering Projects & Ideas For Beginners [2024]
40152
Data engineering is an exciting and rapidly growing field that focuses on building, maintaining, and improving the systems that collect, store, proces
Read More

by Rohit Sharma

21 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon