Reader small image

You're reading from  MongoDB Fundamentals

Product typeBook
Published inDec 2020
PublisherPackt
ISBN-139781839210648
Edition1st Edition
Tools
Concepts
Right arrow
Authors (4):
Amit Phaltankar
Amit Phaltankar
author image
Amit Phaltankar

Amit Phaltankar is a software developer and a blogger experienced in building lightweight and efficient software components. He specializes in wiring web-based applications and handling large-scale data sets using traditional SQL, NoSQL, and big data technologies. He is experienced in many technology stacks and loves learning and adapting to newer technology trends. Amit is passionate about improving his skill set and loves guiding and grooming his peers and contributing to blogs. He is also an author of MongoDB Fundamentals.
Read more about Amit Phaltankar

Juned Ahsan
Juned Ahsan
author image
Juned Ahsan

Juned Ahsan is a software professional with more than 14 years of experience. He has built software products and services for companies and clients such as Cisco, Nuamedia, IBM, Nokia, Telstra, Optus, Pizzahut, AT&T, Hughes, Altran, and others. Juned has a vast experience in building software products and architecting platforms of different sizes from scratch. He loves to help and mentor others and is a top 1% contributor on StackOverflow. He is passionate about cognitive CX, cloud computing, artificial intelligence, and NoSQL databases.
Read more about Juned Ahsan

Michael Harrison
Michael Harrison
author image
Michael Harrison

Michael Harrison started his career at the Australian telecommunications leader Telstra. He worked across their networks, big data, and automation teams. He is now a lead software developer and the founding member of Southbank Software, a Melbourne based startup that builds tools for the next generation of database technologies.
Read more about Michael Harrison

Liviu Nedov
Liviu Nedov
author image
Liviu Nedov

Liviu Nedov is a senior consultant with more than 20 years of experience in database technologies. He has provided professional and consulting services to customers in Australia and Europe. Throughout his career, he has designed and implemented large enterprise projects for customers like Wotif Group, Xstrata Copper/Glencore, and the University of Newcastle and Energy, Queensland. He is currently working at Data Intensity, which is the largest multi-cloud service provider for applications, databases, and business intelligence. In recent years, he is actively involved in MongoDB NoSQL database projects, database migrations, and cloud DBaaS (Database as a Service) projects.
Read more about Liviu Nedov

View More author details
Right arrow

5. Inserting, Updating, and Deleting Documents

Overview

This chapter introduces you to the core operations in MongoDB, namely inserting, updating, and deleting documents in a collection. You will learn how to insert a single document or a batch of multiple documents into a MongoDB collection. You will add or autogenerate an _id field, replace existing documents, and update specific fields in the documents of an existing collection. Finally, you will learn how you can delete all or delete specific documents in a collection.

Introduction

In previous chapters, we covered various database commands and queries. We learned to prepare query conditions and use them to find or count the matching documents. We also learned to use various conditional operators, logical operators, and regular expressions on fields, nested fields, and arrays. In addition to these, we learned how to format, skip, limit, and sort the documents in the result set.

Now that you know how to correctly find and represent the required documents from a collection, the next step is to learn how to modify the documents in the collection. When working on any database management system, you will be required to modify the underlying data. Consider this: you are managing our movies dataset and are often required to add new movies to the collection as they release. You will also be required to permanently remove some movies or remove incorrectly inserted movies from the database. Over a period of time, some movies may receive new awards, reviews...

Inserting Documents

In this section, you will learn to insert new documents into a MongoDB collection. MongoDB collections provide a function named insert(), which is used to create a new document in a collection. The function is executed on the collection and takes the document to be inserted as an argument. The syntax of this function is shown in the next command:

db.collection.insert( <Document To Be Inserted>)

To see this in an example, open the mongo Shell, connect to the database cluster, and create a new database by using the use CH05 command. You can give a different name to the database as per your preference. The database mentioned in this command will be created if it is not present earlier. In the following operation, we are inserting a movie with a title field and an _id, and the output is printed on the next line:

> db.new_movies.insert({"_id" : 1, "title" : "Dunkirk"})
WriteResult({ "nInserted" : 1 })

Note...

Deleting Documents

In this section, we will see how to remove the documents from a collection. To delete one or more documents from a collection, we have to use one of the various delete functions provided by MongoDB. Each of these functions has different behaviors and purposes. To delete documents from a collection, we have to use one of the delete functions and provide a query condition to specify which documents should be deleted. Let's take a look at this in detail.

Deleting Using deleteOne()

As the name suggests, the function deleteOne() is used to delete a single document from a collection. It accepts a document representing a query condition. Upon successful execution, it returns a document containing the total number of documents deleted (represented by the field deletedCount) and whether the operation was confirmed (given by the field acknowledged). However, as the method deletes only one document, the value of deletedCount is always one. If the given query condition...

Replacing Documents

In this section, you will learn how you can completely replace the documents in a collection.

Sometimes you may want to replace an incorrectly inserted document in a collection. Or consider that, often, the data stored in documents is changed over time. Or, perhaps, to support your product's new requirements, you may want to alter the way your documents are structured or change the fields in your documents. In all such cases, you will need to replace the documents.

In the previous section, we used a new database of CH05 which we will continue using in this section. In the same database, create a collection named users and insert a few users into it, as follows:

> db.users.insertMany([
  {"_id": 2, "name": "Jon Snow", "email": "Jon.Snow@got.es"},
  {"_id": 3, "name": "Joffrey Baratheon", "email":     "Joffrey.Baratheon@got.es...

Modify Fields

In the previous sections, we learned that we could replace any document in a MongoDB collection once it has been inserted. During the replace operation, a document in the database will be replaced with a completely new document while keeping the same primary key. The replacement operations are quite useful when it comes to rectifying errors and to incorporating data changes or updates. However, in most cases, updates will affect only one or a few fields of a document. Think about any movie record from the sample_mflix dataset, where most of its fields (such as the title, cast, directors, duration, and so on) may never change. However, over a period of time, the movie may receive new comments, new reviews, and ratings.

The find and replace operation is very useful when all or most fields of a document are modified. But, using it to update only particular fields in the documents will not be easy. To do so, the replacement document you provide will need to have all the...

Update Operators

In order to facilitate different types of update commands, MongoDB provides various update operators or update modifiers such as set, multiply, increment, and more. In the previous sections, we used the operator $set, which is one of the update operators provided by MongoDB. In this section, we will learn some of the most commonly used operators and examples. Before we go through the operators, we will discuss their syntax. The following code snippet shows the basic syntax of an update expression that uses an update operator:

{
  <update operator>: {<field1> : <value1>, ... }
}

As per the preceding syntax, an operator can be assigned a document containing one or more pairs of field and value. The operator is then applied to each field using the respective value. An update expression like the previous one is useful when all the given fields need to be updated with the same operator. You may also want to update different fields of a...

Summary

We started this chapter with the creation of documents in a collection. We saw that, during an insert operation, MongoDB creates the underlying collection if it does not exist, and autogenerates an _id field if the document does not have one already. We then covered various functions provided by MongoDB to delete and replace one or more documents in a collection, as well as the concept of upsert, its benefits, its support in MongoDB, and how an upsert operation differs from delete and insert. Then we learned how to add, update, rename, or remove fields in MongoDB documents using various functions and operators.

In the next chapter, we will execute some complex update commands using the aggregation pipeline support that was added in MongoDB 4.2, and learn how to modify the elements in an array field.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
MongoDB Fundamentals
Published in: Dec 2020Publisher: PacktISBN-13: 9781839210648
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (4)

author image
Amit Phaltankar

Amit Phaltankar is a software developer and a blogger experienced in building lightweight and efficient software components. He specializes in wiring web-based applications and handling large-scale data sets using traditional SQL, NoSQL, and big data technologies. He is experienced in many technology stacks and loves learning and adapting to newer technology trends. Amit is passionate about improving his skill set and loves guiding and grooming his peers and contributing to blogs. He is also an author of MongoDB Fundamentals.
Read more about Amit Phaltankar

author image
Juned Ahsan

Juned Ahsan is a software professional with more than 14 years of experience. He has built software products and services for companies and clients such as Cisco, Nuamedia, IBM, Nokia, Telstra, Optus, Pizzahut, AT&T, Hughes, Altran, and others. Juned has a vast experience in building software products and architecting platforms of different sizes from scratch. He loves to help and mentor others and is a top 1% contributor on StackOverflow. He is passionate about cognitive CX, cloud computing, artificial intelligence, and NoSQL databases.
Read more about Juned Ahsan

author image
Michael Harrison

Michael Harrison started his career at the Australian telecommunications leader Telstra. He worked across their networks, big data, and automation teams. He is now a lead software developer and the founding member of Southbank Software, a Melbourne based startup that builds tools for the next generation of database technologies.
Read more about Michael Harrison

author image
Liviu Nedov

Liviu Nedov is a senior consultant with more than 20 years of experience in database technologies. He has provided professional and consulting services to customers in Australia and Europe. Throughout his career, he has designed and implemented large enterprise projects for customers like Wotif Group, Xstrata Copper/Glencore, and the University of Newcastle and Energy, Queensland. He is currently working at Data Intensity, which is the largest multi-cloud service provider for applications, databases, and business intelligence. In recent years, he is actively involved in MongoDB NoSQL database projects, database migrations, and cloud DBaaS (Database as a Service) projects.
Read more about Liviu Nedov