MongoDB Commands

MongoDB shell commands and aggregation pipeline examples

Database Operations

show dbs

List all databases

show dbs

use database

Switch to a database

use myapp

db.dropDatabase()

Delete current database

db.dropDatabase()

db.stats()

Show database statistics

db.stats()

Collection Operations

show collections

List all collections

show collections

db.createCollection()

Create a new collection

db.createCollection("users")

db.collection.drop()

Delete a collection

db.users.drop()

db.collection.stats()

Show collection statistics

db.users.stats()

CRUD Operations

insertOne()

Insert a single document

db.users.insertOne({name: "John", age: 30})

insertMany()

Insert multiple documents

db.users.insertMany([{name: "John"}, {name: "Jane"}])

find()

Query documents

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

findOne()

Find first matching document

db.users.findOne({name: "John"})

updateOne()

Update first matching document

db.users.updateOne({name: "John"}, {$set: {age: 31}})

updateMany()

Update all matching documents

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

deleteOne()

Delete first matching document

db.users.deleteOne({name: "John"})

deleteMany()

Delete all matching documents

db.users.deleteMany({age: {$lt: 18}})

Query Operators

$eq

Equal to

db.users.find({age: {$eq: 30}})

$gt, $gte

Greater than, greater than or equal

db.users.find({age: {$gt: 25, $lte: 50}})

$lt, $lte

Less than, less than or equal

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

$in, $nin

In array, not in array

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

$and, $or

Logical operators

db.users.find({$and: [{age: {$gt: 25}}, {city: "NYC"}]})

$regex

Regular expression

db.users.find({name: {$regex: "^J"}})

Aggregation Pipeline

$match

Filter documents

db.users.aggregate([{$match: {age: {$gt: 25}}}])

$group

Group documents

db.users.aggregate([{$group: {_id: "$city", count: {$sum: 1}}}])

$sort

Sort documents

db.users.aggregate([{$sort: {age: -1}}])

$limit, $skip

Limit and skip documents

db.users.aggregate([{$skip: 10}, {$limit: 5}])

$project

Select fields

db.users.aggregate([{$project: {name: 1, age: 1, _id: 0}}])

$lookup

Join collections

db.orders.aggregate([{$lookup: {from: "users", localField: "userId", foreignField: "_id", as: "user"}}])

Index Operations

createIndex()

Create an index

db.users.createIndex({email: 1})

createIndex() unique

Create unique index

db.users.createIndex({email: 1}, {unique: true})

getIndexes()

List all indexes

db.users.getIndexes()

dropIndex()

Remove an index

db.users.dropIndex("email_1")

Common Patterns

Basic CRUD Operations

Create, Read, Update, Delete operations

// Create
db.users.insertOne({
  name: "John Doe",
  email: "[email protected]",
  age: 30,
  created_at: new Date()
})

// Read
db.users.find({age: {$gte: 25}}).sort({name: 1})

// Update
db.users.updateOne(
  {email: "[email protected]"},
  {$set: {age: 31, updated_at: new Date()}}
)

// Delete
db.users.deleteOne({email: "[email protected]"})

Complex Aggregation

Multi-stage aggregation pipeline

db.orders.aggregate([
  // Match orders from last month
  {
    $match: {
      created_at: {
        $gte: new Date("2024-01-01"),
        $lt: new Date("2024-02-01")
      }
    }
  },
  // Lookup user information
  {
    $lookup: {
      from: "users",
      localField: "user_id",
      foreignField: "_id",
      as: "user"
    }
  },
  // Group by user and calculate totals
  {
    $group: {
      _id: "$user_id",
      total_orders: {$sum: 1},
      total_amount: {$sum: "$amount"},
      user_name: {$first: "$user.name"}
    }
  },
  // Sort by total amount
  {
    $sort: {total_amount: -1}
  }
])

Text Search

Full-text search operations

// Create text index
db.products.createIndex({name: "text", description: "text"})

// Search for products
db.products.find({
  $text: {
    $search: "laptop computer",
    $caseSensitive: false
  }
}, {
  score: {$meta: "textScore"}
}).sort({score: {$meta: "textScore"}})

Data Validation

Schema validation for collections

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name: {
          bsonType: "string",
          minLength: 2
        },
        email: {
          bsonType: "string",
          pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 120
        }
      }
    }
  }
})

Tips & Best Practices

Always use indexes for frequently queried fields

Use explain() to analyze query performance

Embed related data when it's small and doesn't change often

Use $lookup for large or frequently changing related data

Implement data validation using schema validation