A Guide to CRUD Operations in MongoDB
CRUD is an acronym for the four fundamental operations of data management: Create, Read, Update, and Delete.
Database and Collection Management
Before performing CRUD operations select a database and collection to work with.
- List all available databases:
show dbs- Create or switch to a database: The
usecommand selects a database. If the database doesn't exist, MongoDB creates it in memory and saves it to disk once you insert the first document.
use CollegeDB
// Switches to CollegeDB, creating it if it doesn't exist- List all collections in the current database:
show collections- Create a new collection: While inserting a document can implicitly create a collection, you can also create one explicitly to define options like validation rules or capped sizes.
db.createCollection("Students")Create: Inserting Documents
A. Insert a Single Document (insertOne)
Use insertOne() to add a single document to a collection. MongoDB automatically adds a unique _id field if you don't provide one.
db.Students.insertOne({
name: "Alice",
age: 21,
major: "Computer Science",
status: "Active"
})B. Insert Multiple Documents (insertMany)
Use insertMany() to add an array of documents in a single operation. This is far more efficient than inserting documents one by one.
db.Students.insertMany([
{ name: "Bob", age: 22, major: "Physics", status: "Active" },
{ name: "Charlie", age: 20, major: "Math", status: "Inactive" },
{ name: "David", age: 22, major: "Computer Science", gpa: 3.8 }
])Creating another Collection:
db.Courses.insertMany([
{ courseID: "CS101", title: "Intro to CS", credits: 3 },
{ courseID: "MA101", title: "Calculus", credits: 4 }
])Read: Querying Documents
A. Find All Documents (find)
To retrieve all documents in a collection, use the find() method with no arguments.
db.Students.find()B. Find Documents with a Filter
Pass a query document to find() to filter results based on specific criteria.
- Equality Match:
db.Students.find({ name: "David" })- Using Query Operators: Query operators, like
$gt(greater than), allow for more complex comparisons.
// Find all students older than 20
db.Students.find({ age: { $gt: 20 } })C. Find a Single Document (findOne)
To retrieve the first document that matches a query, use findOne(). It is faster than find() if you only need one result.
db.Students.findOne({ major: "Computer Science" })D. Query Projection: Selecting Specific Fields
By default, queries return all fields. To limit the fields returned, add a projection object as the second argument to your find method.
1: Include the field.0: Exclude the field.
// Include only the name and major fields
// the _id is included by default
db.Students.find(
{ major: "Computer Science" },
{ name: 1, major: 1 }
)
// Exclude the age and status fields
db.Students.find(
{ major: "Computer Science" },
{ age: 0, status: 0 }
)Note: You cannot mix
1and0in a projection, except to explicitly exclude the_idfield:{ _id: 0, name: 1, major: 1 }.
Update: Modifying Documents
MongoDB provides several atomic operators to modify documents. It is crucial to use these operators (like $set, $inc, $push) to avoid accidentally replacing the entire document.
A. Update a Single Document (updateOne)
updateOne modifies the first document that matches the filter.
// SYNTAX
db.collection.updateOne(
{ filter },
{ $set: { field1: value1, field2: value2, ... } }
)Example: Let's update Alice's major and add a graduation year.
db.Students.updateOne(
{ name: "Alice" },
{ $set: { major: "Data Science", graduationYear: 2026 } }
)- The
$setoperator updates the value of a field. If the field does not exist,$setadds a new field with the specified value.
B. The Danger of Updating Without $set
If you omit the update operator, MongoDB replaces the entire document with the one you provide, keeping only the _id.
// INCORRECT:
db.Students.updateOne(
{ name: "Alice" },
{ gpa: 3.9 }
// All other fields are removed!
)C. Update Multiple Documents (updateMany)
updateMany modifies all documents that match the filter.
// Sets the status of all students older than 21 to "Alumni"
db.Students.updateMany(
{ age: { $gt: 21 } },
{ $set: { status: "Alumni" } }
)D. Incrementing a Value ($inc)
The $inc operator is used to increment (or decrement) the value of a field by a specified amount.
// Increment Alice's age by 1
db.Students.updateOne(
{ name: "Alice" },
{ $inc: { age: 1 } }
)Manipulating Arrays and Fields
MongoDB has powerful operators for managing arrays and individual fields within documents.
Let's assume we have a cars collection:
{
"model": "Nexon",
"features": ["Airbags", "ABS", "Sunroof"],
"tags": ["suv", "compact"]
}A. Adding Elements to an Array
$push: Adds an element to an array. Duplicates are allowed.
// Adds "Heated Seats" to the features array
db.cars.updateOne(
{ model: "Nexon" },
{ $push: { features: "Heated Seats" } }
)$addToSet: Adds an element only if it does not already exist in the array.
// This will do nothing if "Sunroof" is already in the array
db.cars.updateOne(
{ model: "Nexon" },
{ $addToSet: { features: "Sunroof" } }
)$each: Use with$pushor$addToSetto add multiple values at once.
db.cars.updateOne(
{ model: "Nexon" },
{ $addToSet: { features: { $each: ["GPS", "Bluetooth"] } } }
)B. Removing Elements and Fields
$pull: Removes all instances of a value from an array.
// Removes "Sunroof" from the features array
db.cars.updateOne(
{ model: "Nexon" },
{ $pull: { features: "Sunroof" } }
)$unset: Completely removes a field from a document.
// Removes the "tags" field entirely
db.cars.updateOne(
{ model: "Nexon" },
{ $unset: { tags: "" } }
// The value assigned to $unset doesn't matter
)Delete: Removing Documents and Collections
A. Delete a Single Document (deleteOne)
deleteOne removes the first document that matches the filter.
db.Students.deleteOne({ name: "Charlie" })B. Delete Multiple Documents (deleteMany)
deleteMany removes all documents that match the filter. Providing an empty filter {} will delete all documents in the collection.
// Deletes all students with the "Inactive" status
db.Students.deleteMany({ status: "Inactive" })
db.Students.deleteMany({ age: { $gt: 21 } })C. Drop a Collection (drop)
To delete an entire collection, including all of its documents and indexes, use the drop() method. This is much faster than deleteMany({}).
db.Students.drop()D. Drop a Database (dropDatabase)
To delete the entire current database, including all its collections:
db.dropDatabase()Warning: This command is irreversible. Use with extreme caution.
Quick Reference: Operators and Commands
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
$eq | Equal to | { age: { $eq: 22 } } |
$ne | Not equal to | { status: { $ne: "Active" } } |
$gt | Greater than | { age: { $gt: 20 } } |
$gte | Greater than or equal to | { gpa: { $gte: 3.5 } } |
$lt | Less than | { age: { $lt: 25 } } |
$lte | Less than or equal to | { age: { $lte: 30 } } |
$in | Value is in an array | { major: { $in: ["CS", "Math"] } } |
$nin | Value is not in an array | { major: { $nin: ["Physics"] } } |
Update Operators
| Operator | Meaning | Example |
|---|---|---|
$set | Sets or updates the value of a field. | { $set: { price: 999 } } |
$inc | Increments a numeric field by a given amount. | { $inc: { quantity: -2 } } |
$unset | Removes a field from a document. | { $unset: { oldField: "" } } |
$push | Adds an element to an array (allows duplicates). | { $push: { tags: "sale" } } |
$addToSet | Adds an element to an array only if it's not present. | { $addToSet: { tags: "unique" } } |
$pull | Removes all instances of a value from an array. | { $pull: { tags: "sale" } } |
$each | Modifier for $push or $addToSet to add multiple items. | { $push: { tags: { $each: ["a", "b"] } } } |
