logo
eng-flag

MongoDB Cheatsheet

Table of Contents

  1. Basic Commands
  2. Database Operations
  3. Collection Operations
  4. Document Operations
  5. Querying Data
  6. Update Operations
  7. Delete Operations
  8. Aggregation
  9. Indexing
  10. User Management
  11. Backup and Restore
  12. Replication
  13. Sharding
  14. Performance Tuning

Basic Commands

Start MongoDB

mongod

Connect to MongoDB

mongo

Show current database

db

Show all databases

show dbs

Switch to a database

use database_name

Show all collections in current database

show collections

Database Operations

Create a new database

use new_database

Drop a database

use database_to_drop
db.dropDatabase()

Collection Operations

Create a new collection

db.createCollection("collection_name")

Drop a collection

db.collection_name.drop()

Document Operations

Insert a document

db.collection_name.insertOne({
  field1: "value1",
  field2: "value2"
})

Insert multiple documents

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

Querying Data

Find all documents in a collection

db.collection_name.find()

Find documents with a specific condition

db.collection_name.find({ field: "value" })

Find one document

db.collection_name.findOne({ field: "value" })

Limit the result

db.collection_name.find().limit(5)

Sort the result

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

Count documents

db.collection_name.countDocuments({ field: "value" })

Comparison Operators

db.collection_name.find({ field: { $gt: value } })  // greater than
db.collection_name.find({ field: { $lt: value } })  // less than
db.collection_name.find({ field: { $gte: value } }) // greater than or equal
db.collection_name.find({ field: { $lte: value } }) // less than or equal
db.collection_name.find({ field: { $ne: value } })  // not equal
db.collection_name.find({ field: { $in: [value1, value2] } }) // in array

Logical Operators

db.collection_name.find({ $and: [{ field1: "value1" }, { field2: "value2" }] })
db.collection_name.find({ $or: [{ field1: "value1" }, { field2: "value2" }] })
db.collection_name.find({ field: { $not: { $eq: value } } })

Update Operations

Update a single document

db.collection_name.updateOne(
  { field: "value" },
  { $set: { field_to_update: "new_value" } }
)

Update multiple documents

db.collection_name.updateMany(
  { field: "value" },
  { $set: { field_to_update: "new_value" } }
)

Replace a document

db.collection_name.replaceOne(
  { field: "value" },
  { new_field1: "new_value1", new_field2: "new_value2" }
)

Delete Operations

Delete a single document

db.collection_name.deleteOne({ field: "value" })

Delete multiple documents

db.collection_name.deleteMany({ field: "value" })

Aggregation

Basic Aggregation

db.collection_name.aggregate([
  { $match: { field: "value" } },
  { $group: { _id: "$group_field", total: { $sum: "$sum_field" } } },
  { $sort: { total: -1 } }
])

Aggregation Stages

// $match
db.collection_name.aggregate([
  { $match: { status: "active" } }
])

// $group
db.collection_name.aggregate([
  { $group: { _id: "$category", count: { $sum: 1 } } }
])

// $project
db.collection_name.aggregate([
  { $project: { field1: 1, field2: 1, _id: 0 } }
])

// $sort
db.collection_name.aggregate([
  { $sort: { field: 1 } }
])

// $limit
db.collection_name.aggregate([
  { $limit: 5 }
])

// $unwind
db.collection_name.aggregate([
  { $unwind: "$array_field" }
])

Indexing

Create an index

db.collection_name.createIndex({ field: 1 })  // 1 for ascending, -1 for descending

Create a unique index

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

List all indexes

db.collection_name.getIndexes()

Drop an index

db.collection_name.dropIndex("index_name")

User Management

Create a user

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

Grant roles to user

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

Show users

db.getUsers()

Delete a user

db.dropUser("username")

Backup and Restore

Create a backup

mongodump --db database_name --out backup_directory

Restore from backup

mongorestore --db database_name backup_directory

Replication

Configure a replica set

In the MongoDB configuration file (mongod.conf):

replication:
  replSetName: "rs0"

Initiate the replica set

rs.initiate()

Add members to the replica set

rs.add("hostname:port")

Check replica set status

rs.status()

Sharding

Enable sharding for a database

sh.enableSharding("database_name")

Shard a collection

sh.shardCollection("database_name.collection_name", { "shard_key": 1 })

Add a shard

sh.addShard("hostname:port")

Check sharding status

sh.status()

Performance Tuning

Explain a query

db.collection_name.find({ field: "value" }).explain("executionStats")

Get collection statistics

db.collection_name.stats()

Get database statistics

db.stats()

Profile queries

db.setProfilingLevel(1)  // 0: off, 1: slow queries, 2: all queries

View profiler data

db.system.profile.find().pretty()

2024 © All rights reserved - buraxta.com