Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
MongoDB Fundamentals

You're reading from  MongoDB Fundamentals

Product type Book
Published in Dec 2020
Publisher Packt
ISBN-13 9781839210648
Pages 748 pages
Edition 1st Edition
Languages
Concepts
Authors (4):
Amit Phaltankar Amit Phaltankar
Profile icon Amit Phaltankar
Juned Ahsan Juned Ahsan
Profile icon Juned Ahsan
Michael Harrison Michael Harrison
Profile icon Michael Harrison
Liviu Nedov Liviu Nedov
Profile icon Liviu Nedov
View More author details

Table of Contents (15) Chapters

Preface
1. Introduction to MongoDB 2. Documents and Data Types 3. Servers and Clients 4. Querying Documents 5. Inserting, Updating, and Deleting Documents 6. Updating with Aggregation Pipelines and Arrays 7. Data Aggregation 8. Coding JavaScript in MongoDB 9. Performance 10. Replication 11. Backup and Restore in MongoDB 12. Data Visualization 13. MongoDB Case Study Appendix

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 2020 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}