MongoDB Zero to Hero: CRUD Operations in MongoDB (Part 2)

In MongoDB Zero to Hero: Understanding MongoDB from Scratch (Part 1), we explored the fundamentals of MongoDB, including the document model, JSON vs BSON, the _id field, MongoDB architecture, it’s key componets, etc.  

Now that we understand how MongoDB works, it’s time to get our hands dirty. 

In this part, we’ll learn how to create, read, update and delete documents in MongoDB, the four basic operations commonly known as CRUD. 

By the end of this article, you’ll know how to: 

  • Create databases and collections  
  • Insert documents  
  • Retrieve documents using queries  
  • Filter data using query operators  
  • Update existing documents  
  • Delete documents  
  • Work with arrays and nested documents  

We’ll use a simple e-commerce application throughout this article so that each operation is easy to understand. 

What is CRUD?

CRUD stands for: 

C → Create
R → Read
U → Update
D → Delete 

These are the four basic operations we perform on data. 

1. Create Operations: 

  • Create operations add new documents to a collection. If the collection does not exist yet, MongoDB will automatically create it. 
  • We use insertOne() and insertMany() to insert documents in collections. 
  • insertOne() → inserts one document into a collection.  
  • insertMany() → inserts multiple documents into a collection. 

Using insertOne() 

db.products.insertOne({
  productName: "Laptop",
  price: 64999
})

Using insertMany()

db.products.insertMany([
  {
    productName: "Laptop",
    price: 64999
  },
  {
    productName: "Mouse",
    price: 799
  }
])

Here products is the collection name. 

2. Read Operations 

  • Read operations are used to retrieve or query documents from a MongoDB collection. 
  • MongoDB provides the find() and findOne() methods for reading documents from a collection 
  • findOne(): Returns the first document that matches the query filter 
  • find(): Returns a cursor pointing to all matching documents 

find():

Return all documents from the products collection. 

db.products.find()

Returns all products where the brand is Dell. 

db.products.find({
  "brand": "Dell"
})

findOne(): 

Search the products collection and returns the first matching document 

db.products.findOne({
  "productName": "Laptop"
})

Suppose our collection contains: 

[
  {
    "productName": "Laptop",
    "brand": "Dell",
    "price": 64999
  },
  {
    "productName": "Monitor",
    "brand": "Dell",
    "price": 15999
  },
  {
    "productName": "Phone",
    "brand": "Samsung",
    "price": 32999
  }
]

If we want to get only Laptop and Monitor documents. Then run below query using find() 

db.products.find({
  "brand": "Dell"
})

If you want only one maching document then run below query using findOne() 

db.products.findOne({
  "brand": "Dell"
})

3. Update Operations: 

  • Update operations are used to change existing documents in a MongoDB collection. You can update one or multiple documents by specifying a condition that identifies which documents should be changed. 
  • MongoDB provides methods such as: 
  • updateOne() – updates one matching document.  
  • updateMany() – updates multiple matching documents.  
  • replaceOne() – replaces an entire document. 

updateOne():

Suppose we have a products collection: 

{
  "productName": "Laptop",
  "brand": "Dell",
  "price": 64999
}

Now, suppose the laptop price changes from ₹64,999 to ₹69,999. 

We can update the document using updateOne(): 

db.products.updateOne(
  { "productName": "Laptop" },
  { "$set": { "price": 69999 } }
)

Here: 

  • { “productName”: “Laptop” } -> finds the document we want to update.  
  • $set –> specifies the field we want to change.  
  • “price”: 69999 –> changes the price to ₹69,999.  

updateMany(): 

If we want to update multiple documents, we can use updateMany(). 

For example, increase the price of all Dell products: 

db.products.updateMany(
  { "brand": "Dell" },
  { "$set": { "price": 70000 } }
)

Here, $set will update the price of every matching product to 70,000 

In simple terms: updateOne() changes one matching document, while updateMany() changes all documents that match the given condition. 

When using updateOne() or updateMany(), you must use update operators to dictate how the document changes: 

  • $set: Overwrites the value of an existing field or creates the field if it does not exist. 
  • $unset: Removes a specified field from a document. 
  • $inc: Increments or decrements a numeric field value by a specified amount. 
  • $push: Appends a specified value into an array field. 
  • $pull: Removes all array elements that match a specified value or condition 

4. Delete Operations 

Delete operations are used to remove existing documents from a MongoDB collection. You can delete a single document or multiple documents by specifying a condition. If required, you can also remove all documents from a collection. 

MongoDB provides two commonly used methods:

  • deleteOne() – removes the first document that matches the condition.  
  • deleteMany() – removes all documents that match the condition 

deleteOne(): 

This will remove one matching document from the collection. 

db.products.deleteOne({
  "productName": "Laptop"
})

deleteMany():  

This will removes all documents where brand is “Dell” 

db.products.deleteMany({
  "brand": "Dell"
})

To remove all documents from a collection:  

db.products.deleteMany({})

Important: Be Careful with Update and Delete Operations 

Before running an update or delete operation, always verify your filter condition carefully. A small mistake in the query can modify or delete more documents than intended. It is a good practice to first run the same condition with find() to check which documents will be affected. For important or production data, take a backup before performing update or delete operations so that the data can be restored if something goes wrong. 

Working with Arrays and Nested Documents

MongoDB documents can contain arrays and nested documents, allowing us to store related information together in a single document.  

Working with Arrays: 

An array allows you to store multiple values in a single field. 

For example: 

{
  "productName": "Laptop",
  "brand": "Dell",
  "colors": ["Black", "Silver", "Blue"]
}

Here, colors is an array containing multiple values. 

You can search for products that have a specific color: 

db.products.find({
  "colors": "Black"
})

MongoDB will return documents where the colors array contains “Black”. 

You can also store an array of objects: 

{
  "productName": "Laptop",
  "reviews": [
    {
      "user": "John",
      "rating": 5
    },
    {
      "user": "David",
      "rating": 4
    }
  ]
}

This is useful when a document contains a list of related items, such as reviews, order items, tags, or product specifications. 

Working with Nested Documents:

nested document is a document stored inside another document. 

For example: 

{
  "productName": "Laptop",
  "brand": "Dell",
  "price": 70000,
  "specifications": {
    "ram": "16GB",
    "storage": "512GB SSD",
    "processor": "Intel i7"
  }
}

Here, specifications is a nested document containing its own fields. 

You can query a field inside the nested document using dot notation: 

db.products.find({
  "specifications.ram": "16GB"
})

This finds products where the RAM is 16GB. 

Conclusion

We learned how to insert documents using insertOne() and insertMany(), retrieve data using find() and findOne(), modify documents using updateOne() and updateMany(), and remove documents using deleteOne() and deleteMany(). We also explored arrays, nested documents. 

One important lesson is to always verify your query before running update or delete operations, especially when working with multiple documents. For important data, taking a backup before making changes is also a good practice. 

Related Searches

Related Solutions