MongoDB CRUD Operations

CRUD stands for Create, Read, Update, and Delete. These four operations form the foundation of working with any database. In MongoDB, every interaction with data — whether adding a new record, fetching existing ones, changing values, or removing records — falls into one of these four categories.

All examples below use a collection called students inside a database called schoolDB.

use schoolDB

1. Create — Inserting Documents

Inserting means adding new documents to a collection. MongoDB provides two methods for this: insertOne() for a single document and insertMany() for multiple documents at once.

insertOne() — Insert a Single Document

db.students.insertOne({
  name: "Arjun Mehta",
  age: 20,
  course: "Mathematics",
  city: "Jaipur"
})

Output:

{
  acknowledged: true,
  insertedId: ObjectId("64f1a2b3c4d5e6f7a8b9c0d1")
}

MongoDB confirms the insertion and returns the automatically generated _id for the new document.

insertMany() — Insert Multiple Documents

db.students.insertMany([
  { name: "Sneha Gupta", age: 22, course: "Physics", city: "Mumbai" },
  { name: "Rahul Tiwari", age: 21, course: "Chemistry", city: "Lucknow" },
  { name: "Pooja Desai", age: 23, course: "Biology", city: "Pune" }
])

Output:

{
  acknowledged: true,
  insertedIds: {
    "0": ObjectId("..."),
    "1": ObjectId("..."),
    "2": ObjectId("...")
  }
}

Each document gets its own unique _id, and MongoDB returns all of them together.

2. Read — Finding Documents

Reading means retrieving documents from a collection. MongoDB uses find() to fetch documents and findOne() to get only the first matching document.

find() — Get All Documents

db.students.find()

This returns every document in the students collection.

find() with a Filter — Get Specific Documents

A filter is a condition passed inside the find() method. Only documents matching the condition are returned.

db.students.find({ city: "Mumbai" })

This returns all students where the city field equals "Mumbai".

findOne() — Get the First Matching Document

db.students.findOne({ course: "Physics" })

This returns only the first student document where the course is "Physics," even if multiple matches exist.

find() with Multiple Conditions

db.students.find({ age: 22, city: "Mumbai" })

This returns students who are both 22 years old and from Mumbai. Multiple conditions inside a single {} work as an AND operation by default.

3. Update — Modifying Documents

Updating changes the values of existing fields in a document or adds new fields. MongoDB provides updateOne(), updateMany(), and replaceOne().

updateOne() — Update the First Matching Document

The update operation takes two arguments: a filter (which document to find) and an update (what change to make).

db.students.updateOne(
  { name: "Arjun Mehta" },
  { $set: { city: "Delhi" } }
)

This finds the first document where the name is "Arjun Mehta" and changes the city field to "Delhi." The $set operator updates only the specified field without touching the rest of the document.

updateMany() — Update All Matching Documents

db.students.updateMany(
  { course: "Mathematics" },
  { $set: { department: "Science" } }
)

This adds a department field with the value "Science" to every student enrolled in Mathematics.

Increment a Field with $inc

db.students.updateOne(
  { name: "Sneha Gupta" },
  { $inc: { age: 1 } }
)

The $inc operator increases the age field by 1. It is useful when a value needs to increase or decrease by a specific amount instead of being replaced entirely.

replaceOne() — Replace an Entire Document

db.students.replaceOne(
  { name: "Rahul Tiwari" },
  { name: "Rahul Tiwari", age: 21, course: "Computer Science", city: "Noida" }
)

Unlike updateOne(), which changes only specified fields, replaceOne() replaces the entire document content (except _id).

upsert — Insert if Not Found

db.students.updateOne(
  { name: "Kiran Shah" },
  { $set: { age: 24, course: "History", city: "Ahmedabad" } },
  { upsert: true }
)

When upsert: true is set, MongoDB checks if a matching document exists. If it does, it updates it. If it does not, it inserts a new document with the given data.

4. Delete — Removing Documents

Deleting removes documents from a collection permanently. MongoDB provides deleteOne() and deleteMany().

deleteOne() — Remove the First Matching Document

db.students.deleteOne({ name: "Pooja Desai" })

This removes the first document where the name matches "Pooja Desai."

deleteMany() — Remove All Matching Documents

db.students.deleteMany({ course: "Biology" })

This removes every student document where the course is "Biology."

deleteMany() with an Empty Filter — Delete All Documents

db.students.deleteMany({})

Passing an empty filter {} deletes every document in the collection. The collection itself remains, but all documents inside it are removed.

CRUD Operations — Quick Reference Table

OperationMethodPurpose
CreateinsertOne()Add one document
CreateinsertMany()Add multiple documents
Readfind()Retrieve all or filtered documents
ReadfindOne()Retrieve the first matching document
UpdateupdateOne()Modify the first matching document
UpdateupdateMany()Modify all matching documents
UpdatereplaceOne()Replace an entire document
DeletedeleteOne()Remove the first matching document
DeletedeleteMany()Remove all matching documents

Common Update Operators

OperatorPurposeExample
$setSet a field to a new value{ $set: { age: 25 } }
$unsetRemove a field from a document{ $unset: { city: "" } }
$incIncrease or decrease a numeric field{ $inc: { age: 1 } }
$renameRename a field{ $rename: { "city": "location" } }
$pushAdd an item to an array field{ $push: { subjects: "English" } }
$pullRemove an item from an array field{ $pull: { subjects: "English" } }

Summary

CRUD operations are the core of all database interactions in MongoDB. insertOne() and insertMany() add documents. find() and findOne() retrieve them. updateOne(), updateMany(), and replaceOne() modify existing documents using operators like $set and $inc. deleteOne() and deleteMany() remove documents. Every MongoDB application, regardless of complexity, builds upon these fundamental operations.

Leave a Comment