Skip to content

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:
javascript
show dbs
  • Create or switch to a database: The use command 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.
javascript
use CollegeDB 
// Switches to CollegeDB, creating it if it doesn't exist
  • List all collections in the current database:
javascript
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.
javascript
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.

javascript
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.

javascript
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:

js
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.

javascript
db.Students.find()

B. Find Documents with a Filter

Pass a query document to find() to filter results based on specific criteria.

  • Equality Match:
javascript
db.Students.find({ name: "David" })
  • Using Query Operators: Query operators, like $gt (greater than), allow for more complex comparisons.
javascript
// 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.

javascript
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.
javascript
// 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 1 and 0 in a projection, except to explicitly exclude the _id field: { _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.

javascript
// SYNTAX
db.collection.updateOne(
	{ filter },
	{ $set: { field1: value1, field2: value2, ... } }
)

Example: Let's update Alice's major and add a graduation year.

javascript
db.Students.updateOne(
  { name: "Alice" },
  { $set: { major: "Data Science", graduationYear: 2026 } }
)
  • The $set operator updates the value of a field. If the field does not exist, $set adds 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.

javascript
// 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.

javascript
// 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.

javascript
// 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:

json
{
  "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.
javascript
// 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.
javascript
// This will do nothing if "Sunroof" is already in the array
db.cars.updateOne(
  { model: "Nexon" },
  { $addToSet: { features: "Sunroof" } }
)
  • $each: Use with $push or $addToSet to add multiple values at once.
javascript
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.
javascript
// Removes "Sunroof" from the features array
db.cars.updateOne(
  { model: "Nexon" },
  { $pull: { features: "Sunroof" } }
)
  • $unset: Completely removes a field from a document.
javascript
// 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.

javascript
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.

javascript
// 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({}).

javascript
db.Students.drop()

D. Drop a Database (dropDatabase)

To delete the entire current database, including all its collections:

javascript
db.dropDatabase()

Warning: This command is irreversible. Use with extreme caution.

Quick Reference: Operators and Commands

Comparison Operators

OperatorMeaningExample
$eqEqual to{ age: { $eq: 22 } }
$neNot equal to{ status: { $ne: "Active" } }
$gtGreater than{ age: { $gt: 20 } }
$gteGreater than or equal to{ gpa: { $gte: 3.5 } }
$ltLess than{ age: { $lt: 25 } }
$lteLess than or equal to{ age: { $lte: 30 } }
$inValue is in an array{ major: { $in: ["CS", "Math"] } }
$ninValue is not in an array{ major: { $nin: ["Physics"] } }

Update Operators

OperatorMeaningExample
$setSets or updates the value of a field.{ $set: { price: 999 } }
$incIncrements a numeric field by a given amount.{ $inc: { quantity: -2 } }
$unsetRemoves a field from a document.{ $unset: { oldField: "" } }
$pushAdds an element to an array (allows duplicates).{ $push: { tags: "sale" } }
$addToSetAdds an element to an array only if it's not present.{ $addToSet: { tags: "unique" } }
$pullRemoves all instances of a value from an array.{ $pull: { tags: "sale" } }
$eachModifier for $push or $addToSet to add multiple items.{ $push: { tags: { $each: ["a", "b"] } } }

Made with ❤️ for students, by a fellow learner.