CRUD Operations

Create Operations

Insert One Document

// Basic insert
db.users.insertOne({
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    city: "New York"
})

// Insert with custom ObjectId
db.users.insertOne({
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: "Jane Doe",
    email: "jane@example.com"
})

// Insert with timestamps
db.users.insertOne({
    name: "Bob Smith",
    email: "bob@example.com",
    createdAt: new Date(),
    updatedAt: new Date()
})

// Insert with nested objects
db.users.insertOne({
    name: "Alice Johnson",
    email: "alice@example.com",
    profile: {
        firstName: "Alice",
        lastName: "Johnson",
        bio: "Software Developer"
    },
    preferences: {
        theme: "dark",
        notifications: true
    }
})

Insert Multiple Documents

// Insert array of documents
db.users.insertMany([
    {
        name: "Charlie Brown",
        email: "charlie@example.com",
        age: 25,
        city: "Chicago"
    },
    {
        name: "Diana Prince",
        email: "diana@example.com",
        age: 28,
        city: "Boston"
    },
    {
        name: "Eve Wilson",
        email: "eve@example.com",
        age: 32,
        city: "Seattle"
    }
])

// Insert with ordered option (false = continue on error)
db.users.insertMany([
    { name: "User1", email: "user1@example.com" },
    { name: "User2", email: "user2@example.com" }
], { ordered: false })

// Insert with validation
db.users.insertMany([
    { name: "Valid User", email: "valid@example.com", age: 25 },
    { name: "Another User", email: "another@example.com", age: 30 }
], { 
    ordered: true,
    writeConcern: { w: "majority" }
})

Insert with Upsert

// Insert if not exists, update if exists
db.users.updateOne(
    { email: "john@example.com" },
    {
        $setOnInsert: {
            name: "John Doe",
            email: "john@example.com",
            createdAt: new Date()
        },
        $set: {
            updatedAt: new Date()
        }
    },
    { upsert: true }
)

Read Operations

Find All Documents

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

// Get all documents with pretty formatting
db.users.find().pretty()

// Get all documents as array
db.users.find().toArray()

// Get all documents with limit
db.users.find().limit(10)

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 array contains
db.users.find({ 
    tags: { $in: ["developer", "admin"] } 
})

// Find by regex pattern (case insensitive)
db.users.find({ 
    name: { $regex: /john/i } 
})

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

// Find by nested field
db.users.find({
    "profile.firstName": "Alice"
})

// Find by array element
db.users.find({
    "skills": "JavaScript"
})

Find with Projection

// Include specific fields only
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 
})

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

Find with Sorting

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

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

// Sort by text score (requires text index)
db.users.find({ $text: { $search: "john" } })
   .sort({ score: { $meta: "textScore" } })

// Sort by array length
db.users.find().sort({ $expr: { $size: "$tags" } })

Find with Pagination

// Basic pagination
db.users.find().skip(0).limit(10)   // Page 1
db.users.find().skip(10).limit(10)  // Page 2
db.users.find().skip(20).limit(10)  // Page 3

// Pagination with formula
const page = 3;
const limit = 10;
db.users.find()
   .skip((page - 1) * limit)
   .limit(limit)

// Pagination with sort
db.users.find()
   .sort({ createdAt: -1 })
   .skip(20)
   .limit(10)

Find One Document

// Find first matching document
db.users.findOne({ email: "john@example.com" })

// Find with projection
db.users.findOne(
    { email: "john@example.com" },
    { name: 1, email: 1, _id: 0 }
)

// Find by ObjectId
db.users.findOne({ 
    _id: ObjectId("507f1f77bcf86cd799439011") 
})

// Find with sort (gets first after sorting)
db.users.findOne(
    { city: "New York" },
    { name: 1, age: 1 }
).sort({ age: -1 })

Count Documents

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

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

// Count with options
db.users.countDocuments(
    { age: { $gte: 25 } },
    { limit: 100 }
)

// Count distinct values
db.users.distinct("city").length

Update Operations

Update One Document

// Update single field
db.users.updateOne(
    { email: "john@example.com" },
    { $set: { age: 31 } }
)

// Update multiple fields
db.users.updateOne(
    { email: "john@example.com" },
    { 
        $set: { 
            age: 31,
            updatedAt: new Date(),
            status: "active"
        } 
    }
)

// Update with upsert (create if not exists)
db.users.updateOne(
    { email: "newuser@example.com" },
    { 
        $set: { 
            name: "New User",
            email: "newuser@example.com",
            createdAt: new Date()
        } 
    },
    { upsert: true }
)

// Update with increment
db.users.updateOne(
    { email: "john@example.com" },
    { $inc: { loginCount: 1 } }
)

// Update with multiply
db.users.updateOne(
    { email: "john@example.com" },
    { $mul: { salary: 1.1 } }
)

Update Multiple Documents

// Update all matching documents
db.users.updateMany(
    { city: "New York" },
    { $set: { region: "East Coast" } }
)

// Update with increment
db.users.updateMany(
    { age: { $lt: 30 } },
    { $inc: { age: 1 } }
)

// Update with array operations
db.users.updateMany(
    { tags: { $exists: false } },
    { $set: { tags: [] } }
)

// Update with date
db.users.updateMany(
    { status: "active" },
    { $set: { lastUpdated: new Date() } }
)

Update with Array Operators

// Add to array
db.users.updateOne(
    { email: "john@example.com" },
    { $push: { tags: "developer" } }
)

// Add multiple items to array
db.users.updateOne(
    { email: "john@example.com" },
    { $push: { tags: { $each: ["javascript", "mongodb"] } } }
)

// Add to array with position
db.users.updateOne(
    { email: "john@example.com" },
    { $push: { tags: { $each: ["frontend"], $position: 0 } } }
)

// Remove from array
db.users.updateOne(
    { email: "john@example.com" },
    { $pull: { tags: "old-tag" } }
)

// Remove by condition
db.users.updateOne(
    { email: "john@example.com" },
    { $pull: { tags: { $regex: /old.*/ } } }
)

// Remove first element
db.users.updateOne(
    { email: "john@example.com" },
    { $pop: { tags: -1 } }
)

// Remove last element
db.users.updateOne(
    { email: "john@example.com" },
    { $pop: { tags: 1 } }
)

// Add to array if not exists
db.users.updateOne(
    { email: "john@example.com" },
    { $addToSet: { tags: "unique-tag" } }
)

// Add multiple unique items
db.users.updateOne(
    { email: "john@example.com" },
    { $addToSet: { tags: { $each: ["tag1", "tag2", "tag1"] } } }
)

Update with Field Operators

// Rename field
db.users.updateOne(
    { email: "john@example.com" },
    { $rename: { "oldField": "newField" } }
)

// Remove field
db.users.updateOne(
    { email: "john@example.com" },
    { $unset: { "temporaryField": "" } }
)

// Set field only on insert
db.users.updateOne(
    { email: "john@example.com" },
    { 
        $set: { updatedAt: new Date() },
        $setOnInsert: { createdAt: new Date() }
    },
    { upsert: true }
)

// Update nested field
db.users.updateOne(
    { email: "john@example.com" },
    { $set: { "profile.bio": "Updated bio" } }
)

Replace Document

// Replace entire document
db.users.replaceOne(
    { email: "john@example.com" },
    {
        name: "John Doe Updated",
        email: "john@example.com",
        age: 31,
        city: "New York",
        updatedAt: new Date()
    }
)

// Replace with upsert
db.users.replaceOne(
    { email: "newuser@example.com" },
    {
        name: "New User",
        email: "newuser@example.com",
        createdAt: new Date()
    },
    { upsert: true }
)

Delete Operations

Delete One Document

// Delete by filter
db.users.deleteOne({ email: "john@example.com" })

// Delete by ObjectId
db.users.deleteOne({ 
    _id: ObjectId("507f1f77bcf86cd799439011") 
})

// Delete first matching document
db.users.deleteOne({ city: "New York" })

// Delete with complex filter
db.users.deleteOne({
    age: { $lt: 18 },
    status: "inactive"
})

Delete Multiple Documents

// Delete all matching documents
db.users.deleteMany({ city: "New York" })

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

// Delete by multiple conditions
db.users.deleteMany({
    age: { $lt: 18 },
    status: "inactive"
})

// Delete by array condition
db.users.deleteMany({
    tags: { $in: ["spam", "bot"] }
})

Delete All Documents

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

// Alternative method (deprecated)
db.users.remove({})

// Delete with write concern
db.users.deleteMany({}, { 
    writeConcern: { w: "majority" } 
})

Delete with Conditions

// Delete documents older than 30 days
db.users.deleteMany({
    createdAt: { 
        $lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) 
    }
})

// Delete inactive users
db.users.deleteMany({
    $or: [
        { status: "inactive" },
        { lastLogin: { 
            $lt: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) 
        } }
    ]
})

// Delete users with specific criteria
db.users.deleteMany({
    $and: [
        { age: { $lt: 18 } },
        { email: { $regex: /temp.*/ } },
        { createdAt: { 
            $lt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) 
        } }
    ]
})

Bulk Operations

Bulk Write

// Bulk insert, update, delete
db.users.bulkWrite([
    {
        insertOne: {
            document: {
                name: "Bulk User 1",
                email: "bulk1@example.com"
            }
        }
    },
    {
        updateOne: {
            filter: { email: "john@example.com" },
            update: { $set: { status: "updated" } }
        }
    },
    {
        deleteOne: {
            filter: { email: "old@example.com" }
        }
    }
])

Bulk Operations with Options

// Bulk operations with ordered option
db.users.bulkWrite([
    { insertOne: { document: { name: "User1", email: "user1@example.com" } } },
    { insertOne: { document: { name: "User2", email: "user2@example.com" } } },
    { updateOne: { filter: { email: "john@example.com" }, update: { $set: { status: "active" } } } }
], { 
    ordered: false,
    writeConcern: { w: "majority" }
})

Last updated