MongoDB Query API

Master CRUD operations and querying

🔍 MongoDB Query API

Learn to create, read, update, and delete data in MongoDB. Master query operators, filters, and advanced techniques to efficiently manipulate your database documents.


// Basic query example
db.users.find({ age: { $gte: 18 } })
                                    

Output:

{ _id: 1, name: "Alice", age: 28 }
{ _id: 2, name: "Bob", age: 35 }

CRUD Operations

CRUD stands for Create, Read, Update, and Delete - the four basic operations for managing data. MongoDB provides intuitive methods for each operation with powerful query capabilities.

Create

Insert new documents

insertOne()
insertMany()
🔍

Read

Query and retrieve documents

find()
findOne()
✏️

Update

Modify existing documents

updateOne()
updateMany()
🗑️

Delete

Remove documents

deleteOne()
deleteMany()

🔹 Create Operations (Insert)

Add new documents to your collections:

🔸 Insert One Document

// Insert a single document
db.users.insertOne({
    name: "Alice",
    email: "[email protected]",
    age: 28,
    active: true
})

Output:

{
  acknowledged: true,
  insertedId: ObjectId("65a1b2c3d4e5f6789...")
}

🔸 Insert Multiple Documents

// Insert multiple documents
db.users.insertMany([
    { name: "Bob", email: "[email protected]", age: 35 },
    { name: "Charlie", email: "[email protected]", age: 42 },
    { name: "Diana", email: "[email protected]", age: 31 }
])

Output:

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

🔹 Read Operations (Query)

Retrieve documents from your collections:

🔸 Find All Documents

// Find all documents
db.users.find()

// Find all with pretty formatting
db.users.find().pretty()

🔸 Find One Document

// Find first matching document
db.users.findOne({ name: "Alice" })

Output:

{
  _id: ObjectId("..."),
  name: "Alice",
  email: "[email protected]",
  age: 28,
  active: true
}

🔸 Find with Filter

// Find users older than 30
db.users.find({ age: { $gt: 30 } })

// Find active users
db.users.find({ active: true })

// Find by multiple conditions
db.users.find({ age: { $gte: 25 }, active: true })

🔸 Projection (Select Fields)

// Return only name and email (exclude _id)
db.users.find({}, { name: 1, email: 1, _id: 0 })

// Exclude specific fields
db.users.find({}, { password: 0 })

Output:

{ name: "Alice", email: "[email protected]" }
{ name: "Bob", email: "[email protected]" }

🔹 Query Operators

Use operators to create powerful queries:

🔸 Comparison Operators

// Equal to
db.users.find({ age: 28 })

// Greater than
db.users.find({ age: { $gt: 30 } })

// Greater than or equal
db.users.find({ age: { $gte: 30 } })

// Less than
db.users.find({ age: { $lt: 40 } })

// Less than or equal
db.users.find({ age: { $lte: 40 } })

// Not equal
db.users.find({ age: { $ne: 28 } })

// In array
db.users.find({ age: { $in: [25, 30, 35] } })

// Not in array
db.users.find({ age: { $nin: [25, 30] } })

🔸 Logical Operators

// AND (implicit)
db.users.find({ age: { $gte: 25 }, active: true })

// OR
db.users.find({
    $or: [
        { age: { $lt: 25 } },
        { age: { $gt: 40 } }
    ]
})

// NOT
db.users.find({ age: { $not: { $gte: 30 } } })

// NOR
db.users.find({
    $nor: [
        { age: { $lt: 25 } },
        { active: false }
    ]
})

🔸 Element Operators

// Field exists
db.users.find({ email: { $exists: true } })

// Field type
db.users.find({ age: { $type: "number" } })

🔹 Update Operations

Modify existing documents in your collections:

🔸 Update One Document

// Update single document
db.users.updateOne(
    { name: "Alice" },
    { $set: { age: 29, city: "New York" } }
)

Output:

{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}

🔸 Update Multiple Documents

// Update all matching documents
db.users.updateMany(
    { age: { $lt: 30 } },
    { $set: { category: "young" } }
)

🔸 Update Operators

// Set field value
db.users.updateOne(
    { name: "Alice" },
    { $set: { email: "[email protected]" } }
)

// Increment numeric field
db.users.updateOne(
    { name: "Alice" },
    { $inc: { age: 1 } }
)

// Multiply field
db.users.updateOne(
    { name: "Alice" },
    { $mul: { score: 1.5 } }
)

// Rename field
db.users.updateOne(
    { name: "Alice" },
    { $rename: { "email": "emailAddress" } }
)

// Remove field
db.users.updateOne(
    { name: "Alice" },
    { $unset: { city: "" } }
)

// Set current date
db.users.updateOne(
    { name: "Alice" },
    { $currentDate: { lastModified: true } }
)

🔸 Array Update Operators

// Add to array
db.users.updateOne(
    { name: "Alice" },
    { $push: { hobbies: "reading" } }
)

// Add multiple to array
db.users.updateOne(
    { name: "Alice" },
    { $push: { hobbies: { $each: ["gaming", "cooking"] } } }
)

// Remove from array
db.users.updateOne(
    { name: "Alice" },
    { $pull: { hobbies: "reading" } }
)

// Add to set (no duplicates)
db.users.updateOne(
    { name: "Alice" },
    { $addToSet: { tags: "premium" } }
)

🔹 Delete Operations

Remove documents from your collections:

🔸 Delete One Document

// Delete first matching document
db.users.deleteOne({ name: "Alice" })

Output:

{
  acknowledged: true,
  deletedCount: 1
}

🔸 Delete Multiple Documents

// Delete all matching documents
db.users.deleteMany({ age: { $lt: 18 } })

// Delete all documents in collection
db.users.deleteMany({})

Output:

{
  acknowledged: true,
  deletedCount: 3
}

🔹 Sorting and Limiting

Control the order and number of results:

// Sort ascending (1) or descending (-1)
db.users.find().sort({ age: 1 })
db.users.find().sort({ age: -1 })

// Sort by multiple fields
db.users.find().sort({ age: -1, name: 1 })

// Limit results
db.users.find().limit(5)

// Skip documents
db.users.find().skip(10)

// Combine sort, limit, and skip
db.users.find()
    .sort({ age: -1 })
    .skip(10)
    .limit(5)

Output:

{ _id: 3, name: "Charlie", age: 42 }
{ _id: 2, name: "Bob", age: 35 }
{ _id: 4, name: "Diana", age: 31 }
{ _id: 1, name: "Alice", age: 28 }
{ _id: 5, name: "Eve", age: 25 }

🔹 Counting Documents

Count documents in collections:

// Count all documents
db.users.countDocuments()

// Count with filter
db.users.countDocuments({ age: { $gte: 30 } })

// Estimated count (faster, less accurate)
db.users.estimatedDocumentCount()

Output:

5
2
5

🔹 Text Search

Search text fields in your documents:

🔸 Create Text Index

// Create text index
db.articles.createIndex({ title: "text", content: "text" })

🔸 Text Search Query

// Search for text
db.articles.find({ $text: { $search: "mongodb tutorial" } })

// Search exact phrase
db.articles.find({ $text: { $search: "\"mongodb tutorial\"" } })

// Exclude words
db.articles.find({ $text: { $search: "mongodb -sql" } })

🔹 Complete CRUD Example

Putting it all together with a practical example:

// Create: Insert products
db.products.insertMany([
    { name: "Laptop", price: 999, category: "Electronics", stock: 50 },
    { name: "Mouse", price: 25, category: "Accessories", stock: 200 },
    { name: "Keyboard", price: 75, category: "Accessories", stock: 150 }
])

// Read: Find products under $100
db.products.find({ price: { $lt: 100 } })

// Update: Increase price by 10%
db.products.updateMany(
    { category: "Accessories" },
    { $mul: { price: 1.1 } }
)

// Update: Decrease stock
db.products.updateOne(
    { name: "Laptop" },
    { $inc: { stock: -1 } }
)

// Read: Find low stock items
db.products.find({ stock: { $lt: 100 } })

// Delete: Remove out of stock items
db.products.deleteMany({ stock: 0 })

// Count: Total products
db.products.countDocuments()

Output:

{ acknowledged: true, insertedIds: {...} }
{ _id: 2, name: "Mouse", price: 25, category: "Accessories", stock: 200 }
{ _id: 3, name: "Keyboard", price: 75, category: "Accessories", stock: 150 }
{ acknowledged: true, matchedCount: 2, modifiedCount: 2 }
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
{ _id: 1, name: "Laptop", price: 999, category: "Electronics", stock: 49 }
{ acknowledged: true, deletedCount: 0 }
3

🧠 Test Your Knowledge

Which method is used to insert a single document?