OfferTransform Your Career with Expert-Led IT Training. Flat discounts active!Explore Now
OnlineITGuru Logo
Others

MongoDB CRUD Operations Explained: Practical Examples

Last updated on Oct 23, 2026

Copy Link:
MongoDB CRUD Operations Explained: Practical Examples

Interaction with Modern Databases

When developing modern apps, it is vital to look for an appropriate solution in terms of efficient data storage. In the case of relational databases, data are structured in tables on the basis of rows, columns, and relations. Nevertheless, such an approach may be regarded as suitable for specific transactional architecture only. Nowadays, distributed applications imply the necessity to work with different types of unstructured data.

To address this problem, MongoDB offers a document-based data model that allows users to store data in dynamic documents. One of the basic concepts, which should be taken into account in terms of working with any type of database, is CRUD which stands for creation, reading, updating, and deleting operations.

All these operations constitute the foundation for almost all the procedures performed in database management systems. Regardless of whether it is shopping cart management, accounting, or social network feeds, it is necessary to know how MongoDB works in these cases.

MongoDB Architecture

Taking all the CRUD operations into consideration, it is necessary to know what kind of architecture is used.

It has been mentioned above that MongoDB keeps data in so-called documents. The document is quite similar to the row in the relation database system but it is much more sophisticated. The document is serialized in Binary JSON or BSON. It is an enhanced version of human-readable format and it consists of such elements as exact floating point numbers, sixty four-bit integers, exact dates and raw binary data.

The documents are organized into logically coherent groups, which act as tables in relational database management system. However, these groups do not follow any schema. As an example, the document in the inventory group may contain data about the size and weight of the shipment being made, while the other document in the same group may contain data about downloads and licensing. The mongodb online classes available at OnlineITGuru this course can assist students seeking to learn about the process of creation of schema and organization of documents step by step.

Every document intended to be stored in the collection has to be assigned an identifier that will be automatically generated in the identity field. However, in case of no identifier generation in the process of document creation, database engine generates the immutable object identifier that consists of twelve bytes. The object identifier is unique globally for the distributed server clusters because of its composition which includes the precise unix epoch timestamp, machine identifiers, process identifiers and auto incremented counters.

Knowing the principles of object identification allows considering four basic CRUD operations in details using practical examples.

Create Operations: Data Ingestion

Create operation is the first step of record creation in the persistent storage. In case of the document database creation, creation implies storing key-value properties, objects and arrays into the document and storing it in the corresponding collection.

Types of data insertion and their behavior

Data ingestion can be carried out by adopting the below-mentioned techniques: Single document ingestion and Batch document ingestion.

In case there is an occurrence of an event inside the application such as registration of a user or completion of receipt of a particular transaction, there occurs single document insertion. First, the database engine checks if the document’s schema is proper and whether an identity field exists inside the document or not, and then the content of the document gets stored inside the storage file.

In case there are many transactions occurring, for instance, ingestion of data from the smart device, migration of large amounts of data, and ingestion of audit logs, then the insertion of individual documents causes network latency. In such a case, MongoDB supports the use of batch document ingestion. In this case, instead of inserting individual documents via the network, an array of documents gets inserted at once.

Batch operations of the engine can happen both in ordered and unordered manners. In the case when the ordered batch insertion happens, the documents get inserted sequentially. In case any error appears, like a uniqueness violation due to ID collision, then the process gets stopped but the inserted documents remain intact whereas the rest are rejected. The unordered batch insertion tries to insert all the documents regardless of errors occurred during the process and return errors at the end of it.

Scenario of Practical Implementation: Customer Profile Creation

When the customer joins the enterprise's e-commerce application, the customer profile includes his unique ID, email address, phone number, and the preference of communication methods.

Unlike the traditional relational database where the customer's contact details, delivery address, and marketing indicators stored in three separate tables linked via foreign keys, MongoDB provides storing all this related data in one document. Here the address considered as the subdocument, including street, city, postal region, and country name.

As soon as the create command is executed, the entire customer object will be saved onto the disk with just a single disk write, thereby completely eliminating the need for the multi-table join for any further retrieval.

Reading Operations: Searching and Extraction of Information

Now that the information is stored inside the database, the following operation, reading, enables the user to obtain the information according to some parameters. There are two types of reading operations in the MongoDB database: retrieving individual objects according to the primary key and multi-criteria queries.

Query Parameters and Extraction Mechanism

For the process of querying to begin, some type of filter should be specified. In cases where the empty query filter is utilized, the system understands this as the request for all the documents in the collection. Using some specific parameters, the system searches for the documents containing these particular values.

There are many comparison and logical operators in MongoDB other than the equal-to comparison operator:

  • Comparison Operators: Help in filtering out data based on numeric comparison, ordering lexicographically, and boundary calculations in cases when it needs to be determined whether the data is greater than, less than, or lies within certain boundaries.

  • Set Membership Operators: Allow searching of data sets in which the field is a member of one of the possible values in the set.

  • Logical Operators: Using logic gates in combination with conditions using logic AND, OR, NOT, and NOR. In the case of more than one field in a query, the logic AND is automatically used.

  • Array and Element Operators: Helps in searching in flexible documents, in which there may be names of fields or arrays to search for documents having certain elements.

Projection: Filtered Returned Documents

In reality, documents become larger because of the metadata that is attached to them. Full documents' return from the database via the network in case the interface requires only the display name of a user leads to the waste of resources, such as bandwidth and computation power.

The solution to this problem is projection when the developer can specify which fields of a document will be returned and which not. Except the one field that is obligatory for unique document identification and will be returned in any case, projection makes sure that only required fields will be serialized, transferred via the network, and deserialized by the client-side application.

Example Use Case: Filtered Products Catalog

Consider the example of a customer browsing products catalog in an online store. Customer chooses some filters: electronics department, customer reviews four stars or higher, available and within certain price range.

To satisfy these requirements, the application uses read operation with the following filtering criteria:

  • Department attribute value equals consumer electronics.

  • Lower bound condition on average customer reviews rating.

  • Upper bound condition on listing price.

  • Inventory count attribute value is strictly greater than zero.

Using projection, the software application asks the server to get the product name, main image URL, and price without the product description, supplier details, warehouses, and versions from memory.

To respond to users, database administrators use compound indexes on category, price, and ratings. Here, the query planner makes use of the small index tree rather than going through millions of raw documents and hence delivers the result in less than a second.

Update Operations: Updating Existing Documents

Dynamic in nature, inventories are either available or orders are pending or completed. Update operation can help to update the record.

Document Replacement and Atomic Operators

The core difference in document updates in MongoDB is document replacement and document updates using atomic operators.

Using document replacement, the existing document is identified with unique identifier and then replaced with a new document except for the immutable document identifier. It can help to reset the state machine but can also lead to data loss.

Targeted field updates, on the other hand, make use of atomic field update operators that allow for changing the value of a certain number of fields in a document, without modifying the rest of the fields:

  • Field Mutation Operators: They allow for updating the value of a specific field, removing any property from a document, or renaming keys in multiple documents.

  • Mathematical Operators: They allow for increasing or decreasing numeric properties by using a delta value. It becomes especially important when trying to avoid race conditions in cases of high concurrency when views are being incremented or bank accounts are being modified.

  • Array Update Operators: They allow for adding items to an array, popping items from the beginning or the end of a list, slicing arrays without altering their maximum length, or adding multiple items.

Upsert Mode

There is also an option to run an update operation in upsert mode. In such a case, the operation will modify:

  • An existing document depending on the filter criteria.

  • A non-existing document, which means that MongoDB will create a completely new document based on the criteria of the query and update operation.

The upsert operation allows skipping pre-read check and branch conditional in application logic.

Practical Example: Inventory Tracking and Cart

For instance, there was a flash sale held on a particular website, during which several people would like to acquire a particular item that is scarce. Then, in case two users attempt to buy that product simultaneously by performing the read operation in memory, reducing its value by one and performing the update, the race condition occurs, leading to the situation of overselling of the goods.

Thanks to the atomic increment operation in MongoDB, the application performs the update request on the document containing a product with a specific ID with the requirement that the quantity of such products must be greater than zero. The result of that process is a decrease in the quantity of goods by one.

Since the update operations done on the same document are atomic, the document gets locked for some period of time, performing the check on how much inventory remains, decreasing its amount and unlocking the document. If the customer tries to buy a product whose amount equals to zero, the update operation is not performed due to the filter.

Delete Operations: Elimination of Stale/Outdated Information

Delete is the fourth element of CRUD and comprises of the deletion of information from the collection.

Granularity of Delete Operation

Like the creation of collection, the deletion of information can be carried out at various levels of granularity.

In case only one piece of information needs to be deleted, then the delete operation will look for the first match in the collection that matches the required conditions and then deletes the record. The delete operation is most often used when an entity is deleted using the unique identifier attribute such as the deletion of the account created by the user or the configuration items deleted by the administrator.

If multiple pieces of information have to be deleted, then the procedure to delete the single piece of information is the same except for the fact that all records that meet the condition will be deleted from the collection. In case there is no filtering criteria, all records in the collection will be deleted.

The process of deleting a whole set is sure to be much faster in contrast to those processes where a lot of documents must be deleted. It is just the removal of the links between the respective data/index files and their links in the file system.

Hard Delete vs. Soft Delete

When using real-world applications, software developers often make a distinction between the hard delete and soft delete operations:

  • Hard Delete: The document is physically removed from the storage engine. The storage space occupied by this document can now be reused by the storage engine and cannot be used to retrieve any data unless the process of restoration from the backup or change stream is done.

  • Soft Delete: The update operation makes changes to the document without physically removing it but rather by adding a delete flag or timestamp to it. All the reading operations will ignore all those documents which have a delete flag.

Soft delete operation is used to ensure the history and protect against accidental deletion and referential integrity of transactions whereas hard delete operation is used to ensure that privacy laws are observed.

Applying the Scenario in the Real World: Life Cycle of Cancellation of Order

Let us use an application of food delivery, for example. In case of placing an order and immediately cancelling it without the start of order preparation in the restaurant, the application must take into account the fact.

If the procedure of the hard delete is used, the entire document with order data is completely removed from the database. While it allows saving space, it does not allow the company to obtain valuable data as the restaurant will not know the reason for allocating the ingredients, the support will not know the cause of cancellation of the transaction, and the financial system will be unable to reconcile payments made through payment gateway authorization hold.

However, in this case, the application runs the update operation and performs the soft deletion of the order with changing the status to "cancelled" with the explanation and timestamp of cancellation. However, in case of unauthenticated session record or temporary cart record being inactive for 24 hours, it is safe to do the hard multi-document delete.

Advanced Constructs for Performing Operations

Apart from the aforementioned basic mechanisms, MongoDB implements more advanced constructs in order to perform CRUD operations in a complex system.

ACID Multi-Document Transactions

Relational databases support ACID transactions for multiple documents, whereas initially, NoSQL databases paid much attention to scalability rather than multi-document ACID transactions due to the way how data was stored in NoSQL databases: documents embedded into each other did not need to communicate with one another. Nevertheless, in certain cases, there may be a necessity to update multiple collections as part of complex business processes.

In a distributed environment, MongoDB supports ACID multi-document transactions. As in relational databases, the application can start a transaction, perform CRUD operations on multiple documents/collections and, if everything goes well, commit the transaction; otherwise, rollback the transaction.

For instance, when processing an order, it is necessary to:

  • Add a document to the orders collection.

  • Reduce the inventory in the inventory collection.

  • Reduce rewards in the customer loyalty program collection.

In relation to the situation in which the balance does not exist, making it impossible to make the loyalty deduction, the whole process of the transaction will be doomed to fail, and therefore fail in the creation of an order and reduction in the inventory.

Bulk Write Operations

Unlike the scenario in which the system is overloaded by massive amount of data input, and consequently making the operations of creating, updating, and deleting unacceptably slow, the bulk write operations offered by MongoDB gives the programmers the opportunity to merge different inserts, updates, replaces, and deletes into one.

It will optimize the I/O process of the database server.

Aggregation Pipeline: Extending the Read Operations

Whereas the read operations offer a simplified means of searching and projecting of documents through queries, it is complicated in computation and grouping. In this regard, the Aggregation Pipeline feature offered by MongoDB will help in this situation.

Aggregation is a process that involves processing of the documents in several stages of pipeline:

  • The documents satisfying the criteria are passed via the match stage.

  • The documents get modified, and the values are calculated based on a particular calculation in the project stage.

  • Array values inside the documents get unpacked and streams of documents are generated in the unwind stage.

  • Grouping of documents gets done with respect to a particular key field and aggregation of sum, average, and distribution statistics is performed in the group stage.

  • In the sort stage, the sorted data gets emitted after grouping.

All the above process is carried out by the database engine itself, which makes it easier for us to convert raw data into business intelligence by automatically performing calculation and transformation processes.

Conclusion

The understanding of MongoDB requires the knowledge of how the basic functioning of MongoDB works. This is because MongoDB uses rows and columns and replaces them with hierarchical documents called BSON.

Data Structure Construction Operations: Building operations necessary for the construction of data structures using only one network operation.

  • Reading Operations: Utilizes expressive queries and projection to enable data fetching without any increase in the payload size.

  • Updation Operations: Utilizes atomic updates to enable simultaneous updation of value and array without any race condition.

  • Deletion Operations: Provides fine-grained control on your data lifecycle taking into account regulatory and audit considerations as well as data storage optimization via hard and soft deletions.

Because of multi-document ACID transaction, bulk execution pipeline, and aggregation having been implemented, this has made the processes that are being carried out using MongoDB operate correctly by dealing with complicated data. This is for individuals who need to learn more about the architecture of the cluster, indexing, and the deployment process at an enterprise level. The mongodb dba online training from OnlineITGuru is the answer.

Why Choose Us

Master Your Future with OnlineITGuru

We don't just provide courses; we build careers. From expert-led live training to dedicated placement support, discover why thousands of professionals trust us for their digital transformation journey.

200+

Partner Companies

$120K

Highest Package

75%

Average Hike

98%

Placement Rate

Reliable Career Partners

Google
Microsoft
Amazon
Meta
Netflix
Apple