MongoDB Query API

MongoDB Query API 📘

The MongoDB Query API is the set of methods and operators used to create, read, update, and delete (CRUD) data in MongoDB.

It is powerful, flexible, and easy to use compared to traditional SQL queries.


1️⃣ Basic Query Structure

db.collection.method(query, projection)
  • query → filter condition

  • projection → fields to include or exclude


2️⃣ Read Operations (Find)

Find all documents

db.students.find()

Find with condition

db.students.find({ age: 22 })

Find one document

db.students.findOne({ name: "Amit" })

3️⃣ Projection (Select Specific Fields)

Include fields:

db.students.find(
{ age: 22 },
{ name: 1, course: 1 }
)

Exclude field:

db.students.find(
{},
{ _id: 0 }
)

4️⃣ Comparison Query Operators

Operator Meaning
$eq equal
$ne not equal
$gt greater than
$gte greater than or equal
$lt less than
$lte less than or equal
$in in array
$nin not in array

Example:

db.students.find({ age: { $gt: 20 } })

5️⃣ Logical Query Operators

$and

db.students.find({
$and: [
{ age: { $gt: 20 } },
{ course: "BA" }
]
})

$or

db.students.find({
$or: [
{ course: "BA" },
{ course: "BSc" }
]
})

$not

db.students.find({
age: { $not: { $lt: 18 } }
})

6️⃣ Element Query Operators

$exists

db.students.find({ phone: { $exists: true } })

$type

db.students.find({ age: { $type: "number" } })

7️⃣ Array Query Operators

$all

db.users.find({
skills: { $all: ["HTML", "CSS"] }
})

$size

db.users.find({
skills: { $size: 3 }
})

8️⃣ Update Operations

Update one

db.students.updateOne(
{ name: "Amit" },
{ $set: { age: 23 } }
)

Update many

db.students.updateMany(
{ course: "BA" },
{ $set: { status: "active" } }
)

Increment value

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

9️⃣ Delete Operations

Delete one

db.students.deleteOne({ name: "Riya" })

Delete many

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

🔟 Sorting, Limiting & Skipping

Sort

db.students.find().sort({ age: -1 })

Limit

db.students.find().limit(5)

Skip

db.students.find().skip(5)

1️⃣1️⃣ Regular Expression (Search)

db.students.find({
name: { $regex: "^A", $options: "i" }
})

1️⃣2️⃣ Count Documents

db.students.countDocuments({ course: "BA" })

SQL vs MongoDB Query Example

SQL

SELECT * FROM students WHERE age > 20;

MongoDB

db.students.find({ age: { $gt: 20 } })

🔑 Summary

  • MongoDB Query API uses JSON-like syntax

  • Supports rich operators

  • Faster and flexible than SQL

  • Ideal for modern applications

You may also like...