Queries

Basic Find Queries

Simple Find Operations

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

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

// Find one document
db.users.findOne()

// Find with limit
db.users.find().limit(10)

// Find with skip
db.users.find().skip(5)

// Find with sort
db.users.find().sort({ name: 1 })  // ascending
db.users.find().sort({ age: -1 })  // descending

Find with Filters

// Find by exact match
db.users.find({ name: "John Doe" })

// Find by multiple conditions
db.users.find({ 
    age: { $gte: 25 }, 
    city: "New York" 
})

// Find by field existence
db.users.find({ email: { $exists: true } })

// Find by field type
db.users.find({ age: { $type: "number" } })

// Find by null values
db.users.find({ middleName: null })

Comparison Operators

Basic Comparison

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

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

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

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

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

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

Array Comparison

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

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

// Array contains element
db.users.find({ tags: "developer" })

// Array contains all elements
db.users.find({ tags: { $all: ["javascript", "mongodb"] } })

// Array size
db.users.find({ tags: { $size: 3 } })

// Array element at position
db.users.find({ "tags.0": "javascript" })

Date Comparison

// Date range
db.users.find({
    createdAt: {
        $gte: new Date("2023-01-01"),
        $lt: new Date("2023-12-31")
    }
})

// Date comparison with current time
db.users.find({
    lastLogin: { $lt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }
})

// Date field exists
db.users.find({ createdAt: { $exists: true } })

Logical Operators

AND Operations

// Implicit AND
db.users.find({ 
    age: { $gte: 25 }, 
    city: "New York",
    status: "active"
})

// Explicit AND
db.users.find({
    $and: [
        { age: { $gte: 25 } },
        { city: "New York" },
        { status: "active" }
    ]
})

OR Operations

// OR operator
db.users.find({
    $or: [
        { city: "New York" },
        { city: "Los Angeles" }
    ]
})

// Multiple OR conditions
db.users.find({
    $or: [
        { age: { $lt: 25 } },
        { age: { $gt: 65 } },
        { status: "vip" }
    ]
})

NOT Operations

// NOT operator
db.users.find({ age: { $not: { $lt: 18 } } })

// NOT with regex
db.users.find({ email: { $not: /gmail\.com$/ } })

// NOT with multiple conditions
db.users.find({
    $not: {
        $or: [
            { status: "inactive" },
            { age: { $lt: 18 } }
        ]
    }
})

NOR Operations

// NOR operator (neither condition is true)
db.users.find({
    $nor: [
        { age: { $lt: 18 } },
        { status: "inactive" }
    ]
})

Element Operators

Field Existence

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

// Field does not exist
db.users.find({ middleName: { $exists: false } })

// Field exists and is not null
db.users.find({ email: { $exists: true, $ne: null } })

Field Type

// Field is string
db.users.find({ name: { $type: "string" } })

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

// Field is array
db.users.find({ tags: { $type: "array" } })

// Field is object
db.users.find({ profile: { $type: "object" } })

// Field is date
db.users.find({ createdAt: { $type: "date" } })

Evaluation Operators

Regex Patterns

// Case insensitive regex
db.users.find({ name: { $regex: /john/i } })

// Case sensitive regex
db.users.find({ email: { $regex: /^john/ } })

// Regex with options
db.users.find({ name: { $regex: "john", $options: "i" } })

// Complex regex patterns
db.users.find({ email: { $regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ } })
// Text search (requires text index)
db.users.find({ $text: { $search: "john developer" } })

// Text search with score
db.users.find({ $text: { $search: "javascript" } })
   .sort({ score: { $meta: "textScore" } })

// Text search with language
db.users.find({ $text: { $search: "developer", $language: "english" } })

Expression Evaluation

// Using $expr for field comparisons
db.users.find({
    $expr: { $gt: ["$age", "$minAge"] }
})

// Using $expr with arithmetic
db.users.find({
    $expr: { $gt: [{ $add: ["$baseSalary", "$bonus"] }, 100000] }
})

// Using $expr with conditional
db.users.find({
    $expr: {
        $cond: {
            if: { $gte: ["$age", 18] },
            then: { $gte: ["$salary", 50000] },
            else: false
        }
    }
})

Array Queries

Array Element Queries

// Array contains element
db.users.find({ skills: "JavaScript" })

// Array contains multiple elements
db.users.find({ skills: { $all: ["JavaScript", "MongoDB"] } })

// Array element matches condition
db.users.find({ "skills": { $elemMatch: { $regex: /^Java/ } } })

// Array element at specific position
db.users.find({ "skills.0": "JavaScript" })

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

Array Element Matching

// Array element with multiple conditions
db.users.find({
    "skills": {
        $elemMatch: {
            $regex: /^Java/,
            $ne: "JavaScript"
        }
    }
})

// Array of objects
db.users.find({
    "projects": {
        $elemMatch: {
            name: "Web App",
            status: "completed"
        }
    }
})

Array Operations

// Array with specific size
db.users.find({ tags: { $size: 2 } })

// Array with minimum size
db.users.find({ tags: { $exists: true, $ne: [] } })

// Array with maximum size
db.users.find({ $expr: { $lte: [{ $size: "$tags" }, 5] } })

Nested Document Queries

Dot Notation

// Query nested field
db.users.find({ "profile.firstName": "John" })

// Query nested array
db.users.find({ "profile.addresses.city": "New York" })

// Query nested object
db.users.find({ "profile.contact.email": "john@example.com" })

Nested Object Matching

// Match entire nested object
db.users.find({
    profile: {
        firstName: "John",
        lastName: "Doe",
        age: 30
    }
})

// Match nested object with conditions
db.users.find({
    "profile.age": { $gte: 25 },
    "profile.city": "New York"
})

Nested Array Queries

// Nested array element
db.users.find({ "profile.addresses.0.city": "New York" })

// Nested array with elemMatch
db.users.find({
    "profile.addresses": {
        $elemMatch: {
            type: "home",
            city: "New York"
        }
    }
})

Projection Queries

Field Selection

// Include specific fields
db.users.find({}, { name: 1, email: 1, _id: 0 })

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

// Include nested fields
db.users.find({}, { 
    "profile.firstName": 1, 
    "profile.lastName": 1, 
    _id: 0 
})

// Mixed inclusion/exclusion
db.users.find({}, { 
    name: 1, 
    email: 1, 
    password: 0, 
    _id: 0 
})

Conditional Projection

// Conditional field inclusion
db.users.find({}, {
    name: 1,
    email: 1,
    age: { $cond: { if: { $gte: ["$age", 18] }, then: "$age", else: "Under 18" } },
    _id: 0
})

// Computed fields
db.users.find({}, {
    name: 1,
    fullName: { $concat: ["$firstName", " ", "$lastName"] },
    _id: 0
})

Aggregation Queries

Basic Aggregation

// Simple aggregation
db.users.aggregate([
    { $match: { age: { $gte: 25 } } },
    { $group: { _id: "$city", count: { $sum: 1 } } },
    { $sort: { count: -1 } }
])

// Aggregation with multiple stages
db.users.aggregate([
    { $match: { status: "active" } },
    { $group: { _id: "$city", avgAge: { $avg: "$age" } } },
    { $sort: { avgAge: -1 } },
    { $limit: 5 }
])

Aggregation Stages

// $match stage
{ $match: { age: { $gte: 25 } } }

// $group stage
{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }

// $sort stage
{ $sort: { age: 1 } }

// $limit stage
{ $limit: 10 }

// $skip stage
{ $skip: 5 }

// $project stage
{ $project: { name: 1, age: 1, _id: 0 } }

// $lookup stage (join)
{
    $lookup: {
        from: "orders",
        localField: "_id",
        foreignField: "userId",
        as: "orders"
    }
}

// $unwind stage
{ $unwind: "$tags" }

Advanced Query Techniques

Compound Queries

// Complex logical query
db.users.find({
    $and: [
        { age: { $gte: 18 } },
        { status: "active" },
        {
            $or: [
                { city: "New York" },
                { city: "Los Angeles" }
            ]
        },
        {
            $not: {
                tags: { $in: ["spam", "bot"] }
            }
        }
    ]
})

Performance Queries

// Covered query (index only)
db.users.find(
    { email: "john@example.com" },
    { _id: 0, email: 1 }
)

// Query with hint
db.users.find({ age: { $gte: 25 } }).hint({ age: 1 })

// Query with explain
db.users.find({ age: { $gte: 25 } }).explain("executionStats")

Geospatial Queries

// Near query
db.users.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [-73.935242, 40.730610]
            },
            $maxDistance: 10000
        }
    }
})

// Within query
db.users.find({
    location: {
        $geoWithin: {
            $centerSphere: [
                [-73.935242, 40.730610], 0.01
            ]
        }
    }
})

Time-based Queries

// Recent documents
db.users.find({
    createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
})

// Documents in date range
db.users.find({
    createdAt: {
        $gte: new Date("2023-01-01"),
        $lt: new Date("2023-12-31")
    }
})

// Documents by day of week
db.users.find({
    $expr: {
        $eq: [{ $dayOfWeek: "$createdAt" }, 1]  // Monday
    }
})

Last updated