Syntax

Database Commands

Show Databases

show dbs

Switch to Database

use database_name

Show Current Database

db

Collection Commands

// Show collections in current database
show collections

// Create collection
db.createCollection("collection_name")

// Drop collection
db.collection_name.drop()

Insert Syntax

// Insert one document
db.collection_name.insertOne({
    field1: "value1",
    field2: "value2",
    field3: 123
})

// Insert multiple documents
db.collection_name.insertMany([
    { field1: "value1", field2: "value2" },
    { field1: "value3", field2: "value4" }
])

Find Syntax

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

// Find with filter
db.collection_name.find({ field: "value" })

// Find with projection (select fields)
db.collection_name.find({}, { field1: 1, field2: 1, _id: 0 })

// Find with sort
db.collection_name.find().sort({ field: 1 })  // 1=ascending, -1=descending

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

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

// Find one document
db.collection_name.findOne({ field: "value" })

Update Syntax

// Update one document
db.collection_name.updateOne(
    { field: "value" },           // Filter
    { $set: { field: "newValue" } }  // Update operation
)

// Update multiple documents
db.collection_name.updateMany(
    { field: "value" },           // Filter
    { $set: { field: "newValue" } }  // Update operation
)

// Replace document
db.collection_name.replaceOne(
    { field: "value" },           // Filter
    { field1: "value1", field2: "value2" }  // New document
)

Delete Syntax

// Delete one document
db.collection_name.deleteOne({ field: "value" })

// Delete multiple documents
db.collection_name.deleteMany({ field: "value" })

// Delete all documents
db.collection_name.deleteMany({})

Comparison Operators

// Equal
{ field: "value" }

// Greater than
{ field: { $gt: value } }

// Less than
{ field: { $lt: value } }

// Greater than or equal
{ field: { $gte: value } }

// Less than or equal
{ field: { $lte: value } }

// Not equal
{ field: { $ne: value } }

// In array
{ field: { $in: [value1, value2, value3] } }

// Not in array
{ field: { $nin: [value1, value2, value3] } }

Logical Operators

// AND (implicit)
{ field1: "value1", field2: "value2" }

// OR
{ $or: [{ field1: "value1" }, { field2: "value2" }] }

// AND with OR
{
    $and: [
        { field1: "value1" },
        { $or: [{ field2: "value2" }, { field3: "value3" }] }
    ]
}

// NOT
{ field: { $not: { $lt: value } } }

Element Operators

// Field exists
{ field: { $exists: true } }

// Field type
{ field: { $type: "string" } }

Evaluation Operators

// Regex pattern
{ field: { $regex: /pattern/i } }

// Text search
{ $text: { $search: "search term" } }

Field Update Operators

// Set field value
{ $set: { field: "newValue" } }

// Increment field value
{ $inc: { field: 1 } }

// Multiply field value
{ $mul: { field: 1.1 } }

// Rename field
{ $rename: { "oldField": "newField" } }

// Remove field
{ $unset: { "fieldToRemove": "" } }

// Set field only on insert
{ $setOnInsert: { field: "value" } }

Array Update Operators

// Add to array
{ $push: { arrayField: "newItem" } }

// Add multiple to array
{ $push: { arrayField: { $each: ["item1", "item2"] } } }

// Remove from array
{ $pull: { arrayField: "itemToRemove" } }

// Remove first element
{ $pop: { arrayField: -1 } }

// Remove last element
{ $pop: { arrayField: 1 } }

// Add to array if not exists
{ $addToSet: { arrayField: "uniqueItem" } }

Basic Pipeline Structure

db.collection_name.aggregate([
    { stage1: { /* stage options */ } },
    { stage2: { /* stage options */ } },
    { stage3: { /* stage options */ } }
])

Common Pipeline Stages

// Match documents
{ $match: { field: "value" } }

// Group documents
{ $group: { _id: "$field", count: { $sum: 1 } } }

// Sort documents
{ $sort: { field: 1 } }  // 1=ascending, -1=descending

// Limit documents
{ $limit: 10 }

// Skip documents
{ $skip: 5 }

// Project fields
{ $project: { field1: 1, field2: 1, _id: 0 } }

// Join collections
{
    $lookup: {
        from: "otherCollection",
        localField: "field",
        foreignField: "field",
        as: "resultArray"
    }
}

// Unwind array
{ $unwind: "$arrayField" }

Arithmetic Operators

{ $sum: "$field" }
{ $avg: "$field" }
{ $min: "$field" }
{ $max: "$field" }
{ $count: {} }

String Operators

{ $toUpper: "$field" }
{ $toLower: "$field" }
{ $concat: ["$field1", " ", "$field2"] }
{ $substr: ["$field", 0, 3] }

Date Operators

{ $year: "$dateField" }
{ $month: "$dateField" }
{ $dayOfMonth: "$dateField" }
{ $dateToString: { format: "%Y-%m-%d", date: "$dateField" } }

Create Index

// Single field index
db.collection_name.createIndex({ field: 1 })

// Compound index
db.collection_name.createIndex({ field1: 1, field2: -1 })

// Unique index
db.collection_name.createIndex({ field: 1 }, { unique: true })

// Text index
db.collection_name.createIndex({ field: "text" })

// Sparse index
db.collection_name.createIndex({ field: 1 }, { sparse: true })

Index Management

// List indexes
db.collection_name.getIndexes()

// Drop index
db.collection_name.dropIndex("index_name")

Create User

use admin
db.createUser({
    user: "username",
    pwd: "password",
    roles: [
        { role: "readWrite", db: "database_name" }
    ]
})

User Operations

List Users

db.getUsers()

Update User

db.updateUser("username", {
    roles: [
        { role: "readWrite", db: "database_name" }
    ]
})

Delete User

db.dropUser("username")

Connection String Syntax

Basic Connection

mongodb://localhost:27017/database_name

With Authentication

mongodb://username:password@localhost:27017/database_name

With Options

mongodb://localhost:27017/database_name?retryWrites=true&w=majority

Replica Set

mongodb://host1:27017,host2:27017,host3:27017/database_name?replicaSet=myReplicaSet

Shell Commands Syntax

Show Current Database

db

Show Collections

db.getCollectionNames()

Clear Screen

cls

Exit Shell

exit

Help

help

Show Stats

db.stats()
db.collection_name.stats()

Print Formatted JSON

printjson({ field: "value" })

Print to Console

print("message")

Load JavaScript File

load("script.js")

Executed JavaScript

eval("db.collection_name.find().count()")

Last updated