MongoDB Essentials

MongoDB queries, aggregation, and Docker setup for document-based NoSQL database.


Docker Setup

Docker Run

 1# Run MongoDB
 2docker run -d \
 3  --name mongodb \
 4  -e MONGO_INITDB_ROOT_USERNAME=admin \
 5  -e MONGO_INITDB_ROOT_PASSWORD=password \
 6  -v mongo-data:/data/db \
 7  -p 27017:27017 \
 8  mongo:7
 9
10# Connect
11docker exec -it mongodb mongosh -u admin -p password

Docker Compose

 1version: '3.8'
 2
 3services:
 4  mongodb:
 5    image: mongo:7
 6    container_name: mongodb
 7    environment:
 8      MONGO_INITDB_ROOT_USERNAME: admin
 9      MONGO_INITDB_ROOT_PASSWORD: password
10      MONGO_INITDB_DATABASE: mydb
11    volumes:
12      - mongo-data:/data/db
13      - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js
14    ports:
15      - "27017:27017"
16    healthcheck:
17      test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/test --quiet
18      interval: 10s
19      timeout: 5s
20      retries: 5
21    restart: unless-stopped
22
23  mongo-express:
24    image: mongo-express:latest
25    container_name: mongo-express
26    environment:
27      ME_CONFIG_MONGODB_ADMINUSERNAME: admin
28      ME_CONFIG_MONGODB_ADMINPASSWORD: password
29      ME_CONFIG_MONGODB_URL: mongodb://admin:password@mongodb:27017/
30    ports:
31      - "8081:8081"
32    depends_on:
33      - mongodb
34    restart: unless-stopped
35
36volumes:
37  mongo-data:

Basic Commands

 1// Show databases
 2show dbs
 3
 4// Use/create database
 5use mydb
 6
 7// Show collections
 8show collections
 9
10// Create collection
11db.createCollection('users')
12
13// Drop collection
14db.users.drop()
15
16// Drop database
17db.dropDatabase()

CRUD Operations

Insert

 1// Insert one
 2db.users.insertOne({
 3    username: 'john_doe',
 4    email: 'john@example.com',
 5    age: 30,
 6    tags: ['developer', 'nodejs'],
 7    address: {
 8        city: 'New York',
 9        country: 'USA'
10    },
11    createdAt: new Date()
12})
13
14// Insert many
15db.users.insertMany([
16    { username: 'alice', email: 'alice@example.com', age: 25 },
17    { username: 'bob', email: 'bob@example.com', age: 35 }
18])

Find

 1// Find all
 2db.users.find()
 3
 4// Find with filter
 5db.users.find({ age: { $gt: 25 } })
 6
 7// Find one
 8db.users.findOne({ username: 'john_doe' })
 9
10// Projection (select fields)
11db.users.find({}, { username: 1, email: 1, _id: 0 })
12
13// Sort
14db.users.find().sort({ age: -1 })
15
16// Limit and skip
17db.users.find().limit(10).skip(20)
18
19// Count
20db.users.countDocuments({ age: { $gt: 25 } })
21
22// Distinct
23db.users.distinct('age')

Update

 1// Update one
 2db.users.updateOne(
 3    { username: 'john_doe' },
 4    { $set: { email: 'newemail@example.com' } }
 5)
 6
 7// Update many
 8db.users.updateMany(
 9    { age: { $lt: 30 } },
10    { $set: { category: 'young' } }
11)
12
13// Replace one
14db.users.replaceOne(
15    { username: 'john_doe' },
16    { username: 'john_doe', email: 'john@example.com', age: 31 }
17)
18
19// Upsert (insert if not exists)
20db.users.updateOne(
21    { username: 'jane' },
22    { $set: { email: 'jane@example.com' } },
23    { upsert: true }
24)
25
26// Update operators
27db.users.updateOne(
28    { username: 'john' },
29    {
30        $set: { email: 'new@example.com' },
31        $inc: { age: 1 },
32        $push: { tags: 'mongodb' },
33        $currentDate: { lastModified: true }
34    }
35)

Delete

1// Delete one
2db.users.deleteOne({ username: 'john_doe' })
3
4// Delete many
5db.users.deleteMany({ age: { $lt: 18 } })
6
7// Delete all
8db.users.deleteMany({})

Query Operators

 1// Comparison
 2db.users.find({ age: { $eq: 30 } })  // Equal
 3db.users.find({ age: { $ne: 30 } })  // Not equal
 4db.users.find({ age: { $gt: 30 } })  // Greater than
 5db.users.find({ age: { $gte: 30 } }) // Greater than or equal
 6db.users.find({ age: { $lt: 30 } })  // Less than
 7db.users.find({ age: { $lte: 30 } }) // Less than or equal
 8db.users.find({ age: { $in: [25, 30, 35] } })
 9db.users.find({ age: { $nin: [25, 30] } })
10
11// Logical
12db.users.find({ $and: [{ age: { $gt: 25 } }, { age: { $lt: 35 } }] })
13db.users.find({ $or: [{ age: { $lt: 25 } }, { age: { $gt: 35 } }] })
14db.users.find({ age: { $not: { $lt: 30 } } })
15
16// Element
17db.users.find({ email: { $exists: true } })
18db.users.find({ age: { $type: 'number' } })
19
20// Array
21db.users.find({ tags: 'developer' })
22db.users.find({ tags: { $all: ['developer', 'nodejs'] } })
23db.users.find({ tags: { $size: 2 } })
24
25// Regex
26db.users.find({ username: /^john/ })
27db.users.find({ email: { $regex: '@gmail.com$' } })

Aggregation Pipeline

 1// Basic aggregation
 2db.orders.aggregate([
 3    { $match: { status: 'completed' } },
 4    { $group: {
 5        _id: '$userId',
 6        totalSpent: { $sum: '$total' },
 7        orderCount: { $sum: 1 }
 8    }},
 9    { $sort: { totalSpent: -1 } },
10    { $limit: 10 }
11])
12
13// Join (lookup)
14db.orders.aggregate([
15    { $lookup: {
16        from: 'users',
17        localField: 'userId',
18        foreignField: '_id',
19        as: 'user'
20    }},
21    { $unwind: '$user' },
22    { $project: {
23        orderId: '$_id',
24        total: 1,
25        username: '$user.username',
26        email: '$user.email'
27    }}
28])
29
30// Group by date
31db.orders.aggregate([
32    { $group: {
33        _id: {
34            year: { $year: '$createdAt' },
35            month: { $month: '$createdAt' }
36        },
37        total: { $sum: '$total' },
38        count: { $sum: 1 }
39    }},
40    { $sort: { '_id.year': -1, '_id.month': -1 } }
41])
42
43// Complex aggregation
44db.products.aggregate([
45    { $match: { price: { $gt: 50 } } },
46    { $group: {
47        _id: '$category',
48        avgPrice: { $avg: '$price' },
49        minPrice: { $min: '$price' },
50        maxPrice: { $max: '$price' },
51        count: { $sum: 1 }
52    }},
53    { $project: {
54        category: '$_id',
55        avgPrice: { $round: ['$avgPrice', 2] },
56        minPrice: 1,
57        maxPrice: 1,
58        count: 1,
59        _id: 0
60    }},
61    { $sort: { avgPrice: -1 } }
62])

Indexes

 1// Create index
 2db.users.createIndex({ email: 1 })
 3
 4// Compound index
 5db.users.createIndex({ username: 1, email: 1 })
 6
 7// Unique index
 8db.users.createIndex({ email: 1 }, { unique: true })
 9
10// Text index (full-text search)
11db.articles.createIndex({ title: 'text', content: 'text' })
12
13// Search with text index
14db.articles.find({ $text: { $search: 'mongodb database' } })
15
16// TTL index (auto-delete after time)
17db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
18
19// List indexes
20db.users.getIndexes()
21
22// Drop index
23db.users.dropIndex('email_1')
24
25// Explain query
26db.users.find({ email: 'test@example.com' }).explain('executionStats')

Python Integration

 1from pymongo import MongoClient
 2from datetime import datetime
 3
 4# Connect
 5client = MongoClient('mongodb://admin:password@localhost:27017/')
 6db = client['mydb']
 7users = db['users']
 8
 9# Insert
10user_id = users.insert_one({
11    'username': 'john_doe',
12    'email': 'john@example.com',
13    'age': 30,
14    'createdAt': datetime.now()
15}).inserted_id
16
17# Find
18user = users.find_one({'username': 'john_doe'})
19print(user)
20
21# Find many
22for user in users.find({'age': {'$gt': 25}}):
23    print(user)
24
25# Update
26users.update_one(
27    {'username': 'john_doe'},
28    {'$set': {'email': 'newemail@example.com'}}
29)
30
31# Delete
32users.delete_one({'username': 'john_doe'})
33
34# Aggregation
35pipeline = [
36    {'$match': {'age': {'$gt': 25}}},
37    {'$group': {
38        '_id': None,
39        'avgAge': {'$avg': '$age'},
40        'count': {'$sum': 1}
41    }}
42]
43result = list(users.aggregate(pipeline))
44print(result)

Related Snippets