How to update existing documents in MongoDB

MongoDB was first developed in 2007 by Dwight Merriman and Eliot Horowitz when they experienced scalability issues with relational databases while developing enterprise web applications at their company, known as DoubleClick. According to one of the developers, its name was derived from the word humongous to support the idea of processing a large amount of data.

The database became an open-source project in 2009 while the company offered commercial support services. Many companies adopted MongoDB because of its unique features. One of these companies was The New York Times newspaper, and they used this database to build a web-based application to submit the photos. In the year 2013, DoubleClick has officially renamed MongoDB Inc.

MongoDB components

Core MongoDB components and their usage include:

  • Collections – Their RDBMS counterparts are tables. They are a set of MongoDB documents
  • Document – Its RDBMS counterpart is Row. This is a collection of data stored in BSON format
  • Field – This is a single element in a MongoDB document that contains values as fields and value pairs.

Document-based storage

A document is a data structure with name-value pairs like JSON, and it is effortless to map any custom Object of any programming language with a MongoDB document. For example, a Student object has attributes such as name, studentid, and subjects where subjects are a List. A document for Students in MongoDB will look like this:

{
Name: "Michael",
Studentid: 1
Subjects: ["Mathematics, English, Geography"]}

You will notice that documents are JSON representations of custom objects from the above representation. Also, excessive JOINS are avoided by saving data in the form of Arrays and documents (Embedded) inside a document.

Updating documentsin MongoDB

MongoDB provides an update () command used to update the documents of a collection. Basic parameters in the command are a condition for which a document needs to be updated and the modification which needs to be performed. A user can add criteria to the update statement to update only selected documents. The example below shows how updating a single value in a document is done:

  • Input the updateOne command.
  • Choose the condition to be used to decide which document is updated. For example, we will update a document with the author and article.
  • Use the set command to modify the Field Name, choose which field name you want to change, then enter the new value as shown below:
db.fossdb.updateOne(
{ item: "article" },
{
$set: { "foss": "fosslinux", author: "Abraham" },
$currentDate: { lastModified: true }
}
)

Output:

update single document
Update single document

Note: ensure to select the correct database using the “use” command. For instance, I am using “fossdb”; therefore, to choose the proper database, I will execute the command below:

use fossdb

Output:

choose database
Choose database

The output will show that one record matched the condition, and therefore the relevant field value in the document is modified.

To update bulk documents simultaneously in MongoDB, a user will need to use a multi-option since, by default, only one document is modified at a time. The code below shows how a user can update many documents at the same time:

  • We will first find the document which has the author as “Abraham” and change the author name from “Abraham” to “Masai.” We will then issue the updateMany command.
  • Then choose the condition to decide which document is to be modified. As mentioned earlier, we will use the document with the “Author” name.
  • Choose the field names you want to update, then enter their new values accordingly.
db.fossdb.updateMany(
{ "articles": { $lt: 50 } },
{
$set: { "foss": "fosslinux", authors: "Masai" },
$currentDate: { lastModified: true }
}
)

Output:

update many docs
Update many docs

After successfully running this command, the output shows that one record matched the condition, and, therefore, the relevant field was modified.

Why users should opt for MongoDB

The following are reasons as to why users should start using MongoDB:

Document oriented

Since this database is a NoSQL type database, data is stored in documents instead of having data in a relational type format. This makes this database very flexible and adaptable to real-world situations and requirements.

Ad hoc queries

Searching by field, queries, and regular expression searches are supported in MongoDB; hence queries can be made to bring back specific fields within documents.

Indexing

Indexes in MongoDB are created to improve the performance of searches within the database.

Load balancing

MongoDB uses sharding to scale horizontally by splitting data across multiple MongoDB instances.

Replication

This database provides high availability with replica sets. Each replica set consists of two or more MongoDB instances. A replica set member may act in the role of the primary or secondary replica at any time. The primary replica is the central server that interacts with the client and performs all the read/write operations. In contrast, the secondary replica maintains a copy of the primary replica using built-in replication data.

Data modeling in MongoDB

From the above discussion, data in Mongo DB has a flexible schema. MongoDB’s collections do not enforce document structure, unlike SQL databases, where a user must declare a table’s schema before inserting data. This sort of flexibility is what makes MongoDB so powerful.

When modeling data in MongoDB, users should keep the following things in mind:

  • Data retrieval patterns – in case of heavy query usage, users should consider using indexes in their data models to improve query efficiency.
  • Application needs – a user should look at the business needs of the application and see what data and type of data are needed for the application.
  • Is the database being modified frequently? – users will have to reconsider the use of indexes or incorporate sharding if required in their data modeling design to improve the efficiency of their overall MongoDB environment.

Conclusion

This article has given a brief analysis of MongoDB, a viral database in the market today. In addition, it has explained how to update existing documents in MongoDB. We hope this article helps you understand MongoDB better. In case of any problem, reach out to us through the comment section, and we will get right back to you.

AD

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

SPONSOR AD
22,858FansLike
452FollowersFollow
16SubscribersSubscribe

More Articles Like This