4 Executing CRUD operations

 

This chapter covers

  • Inserting documents in MongoDB
  • Reading operations from MongoDB
  • Updating operations in MongoDB
  • Removing operations from MongoDB
  • Reviewing MongoDB’s Stable API

CRUD operations involve creating, reading, updating, and deleting documents. These fundamental actions form the backbone of data management systems, allowing applications and users to manipulate data effectively. Each type of CRUD operation has a specific function:

  • Create—Adds new documents to the MongoDB database
  • Read—Retrieves a document from the database
  • Update—Changes details in existing documents within the database
  • Delete—Eliminates documents from the database

CRUD operations define how applications interact with a database by managing the document life cycle, enforcing data consistency, and ensuring efficient access to stored information. This chapter covers executing these operations within MongoDB using mongosh, focusing on their behavior, performance considerations, and best practices for handling data modifications.

4.1 Connecting to mongosh for CRUD operations

Let’s begin exploring CRUD operations. Connect to the MongoDB database in Atlas, which was established in chapter 2. Here’s how you might structure your connection command:

mongosh "mongodb+srv://YOUR_CLUSTER.YOUR_HASH.mongodb.net/" \
--apiVersion API_VERSION --username USERNAME --password PASSWD

4.2 Inserting documents

4.3 Updating documents

4.3.1 Using update operators

4.3.2 Updating many documents

4.4 Updating arrays

4.4.1 Adding elements to an array

4.4.2 Removing elements from an array

4.4.3 Updating array elements

4.4.4 Updating using array filters