MongoDB

MongoDB Bulk Update Example

Hello, in this tutorial, we will see a study and understand the implementation of bulk update in MongoDB. MongoDB update is used to update a document in a collection.

1. Introduction

MongoDB is a document-oriented NoSQL database used for high volume data storage and provides high performance, high availability and automatic scaling.

1.1 What is MongoDB?

  • MongoDB is a NoSQL database where each db contains collections which in turn contains documents. Each document has a different number of fields, size, and content. Each documentation in MongoDB is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent hierarchical relationships, store arrays, and other more complex structures more easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.2 Terminology and Concepts

If you’re not familiar with MongoDB, here’s a quick translation cheat sheet to get you familiar with the terminology:

RDBMSMongoDB
DatabaseDatabase
TableCollection
IndexIndex
RowDocument
ColumnField
JoiningLinking & Embedding
PartitionSharding (Range Partition)
ReplicationReplSet

1.3 Download and Install MongoDB

You can watch this video in order to download and install the MongoDB database on your Windows operating system.

Now, open up the MongoDB workbench and let’s start bulk updating a collection in a NoSQL database!

2. MongoDB Bulk Update Example

In MongoDB, there is no UPDATE statement in MongoDB like there is in SQL.

MongoDB provides the command update() to modify the collection’s documents. To modify the specific documents of a collection, developers can add the criteria to the statement update.

Basic Syntax

> db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA);

In this article, we will perform:

  • A multi-document update operation
  • A single document update operation

2.1 Multi-Document Update Operation

To ensure that multiple documents are updated at the same time in MongoDB, developers need to use the update() reference method. Below we can see how this is achieved:

  1. Execute the command update
  2. Choose the condition for which the document needs to be updated. In our tutorial, we want to update the documents which have the country equal to USA
  3. Run the command set to revise the Field Name
  4. Developers must choose which Field Name they want to change and then they have to enter the new value accordingly

Multi-Document Update Command

> var bulk = db.persons.initializeUnorderedBulkOp();
> bulk.find( { country: "USA" } ).update({$set: {country: "India"}});
> bulk.execute();

If the command is executed successfully and if you run the find command to search for the document, you will have the below output:

Fig. 1: MongoDB Multi Document Update
Fig. 1: MongoDB Multi-Document Update

The result shows that two records matched the condition and hence the required field value was modified.

2.2 Single Document Update Operation

To ensure that single document is updated in MongoDB collection, developers need to use the updateOne() reference method. Below we can see how this is achieved:

  1. Execute the command updateOne
  2. Choose the condition for which the document needs to be updated. In our tutorial, we want to update the document which has the country equal to UK
  3. Run the command set to revise the Field Name
  4. Developers must choose which Field Name they want to change and then they have to enter the new value accordingly

Single Document Update Command

> var bulkOne = db.persons.initializeUnorderedBulkOp();
> bulkOne.find( { country: "UK" } ).updateOne({$set: {country: "Russia"}});
> bulkOne.execute();

Upon a successful execution and if you subsequently execute the find command to search for the specific document, you will have the below output:

Fig. 2: MongoDB Single Document Update
Fig. 2: MongoDB Single Document Update

The result shows that a single record matched the condition and thus the required field value was altered.

2.3 MongoDB Update Document Operators

We have many MongoDB update parameter operators available – most widely used are $set, $inc, $currentDate.

NameDescription
$incIncrements the value of the field by the specified amount
$mulMultiplies the value of the field by the specified amount
$renameRenames a field
$setOnInsertSets the value of a field upon document creation during an upsert.
Has no effect on update operations that modify existing documents
$setSets the value of a field in a document
$unsetRemoves the specified field from a document
$minOnly updates the field if the specified value is less than the existing field value
$maxOnly updates the field if the specified value is greater than the existing field value
$currentDateSets the value of a field to current date, either as a Date or a Timestamp

3. Conclusion

That’s all for MongoDB Bulk Update document examples using MongoDB shell. Do let us know in case you face any problems with it.

4. Download the MongoDB Files

This was an example of MongoDB Bulk Update. Run the script and the result will be printed in the console window.

Download
You can download the full source code of this example here: MongoDB Shell – Executed Commands

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button