MongoDB Cheat Sheet: Essential Commands and Operations

MongoDB is a popular NoSQL database that offers flexibility and scalability for managing large volumes of data. Whether you're a beginner or an experienced developer, having a handy reference for MongoDB commands and operations can streamline your workflow. In this article, we'll cover the essential MongoDB commands and operations in a convenient cheat sheet format.

Introduction

MongoDB is a document-oriented database that stores data in flexible, JSON-like documents. It is designed to be scalable, high-performance, and easy to use.

Basic Commands

  • Show Databases
    show dbs
    
  • Switch Database
    use databaseName
    
  • Show Collections
    show collections
    
  • Create Collection
    db.createCollection("collectionName")
    

CRUD Operations

  • Insert Document
    db.collectionName.insertOne({})
    db.collectionName.insertMany([{}, {}])
  • Find Document
    db.collectionName.find({})
    db.collectionName.findOne({})
    
  • Update Document
    db.collectionName.updateOne({filter}, {$set: {}})
    db.collectionName.updateMany({filter}, {$set: {}})
    
  • Find and Update Documents
    db.collectionName.findOneAndUpdate({filter}, {$set: {}})    # Find and update a document
    
  • Find and Delete Documents
    db.collectionName.findOneAndDelete({filter})
    
  • Find and Replace Documents
    db.collectionName.findOneAndReplace({filter}, {replacement})
    
  • Bulk Write Operations
    db.collectionName.bulkWrite([
      { insertOne: { document: { key: "value" } } },
      { updateMany: { filter: { key: "value" }, update: { $set: { key: "newValue" } } } },
      { deleteOne: { filter: { key: "value" } } }
    ])
  • Delete Document
    db.collectionName.deleteOne({filter})
    db.collectionName.deleteMany({filter})
    

Advanced Operations

  • Sorting Documents
    db.collectionName.find().sort({key: 1})   # Sort documents in ascending order
    
  • Counting Documents
    db.collectionName.find({}).count()        # Count the number of documents in a collection
    
  • Renaming Collections
    db.collectionName.renameCollection("new_coll", true)   # Rename a collection
    
  • Validating Collections
    db.collectionName.validate({full: true})   # Validate a collection, including data and indexes
    
  • Retrieving Collection Size Information
    db.collectionName.totalSize()             # Get the total size of the collection
    db.collectionName.totalIndexSize()        # Get the total index size of the collection
    db.collectionName.storageSize()           # Get the storage size of the collection
    

Indexing

  • Create Index
    db.collectionName.createIndex({key: 1})
    
  • List Indexes
    db.collectionName.getIndexes()
    
  • Drop Index
    db.collectionName.dropIndex("indexName")
    

Aggregation

Aggregation Pipeline

db.collectionName.aggregate([
  { $match: {} },
  { $group: {} }
])

Replication and Sharding

  • Check Replica Set Status
    rs.status()
    
  • Initiate Replica Set
    rs.initiate()
    
  • Enable Sharding
    sh.enableSharding("databaseName")
    
  • Shard a Collection
    sh.shardCollection("databaseName.collectionName", {shardKey: 1})
    

Miscellaneous Operations

  • Backup Database
    mongodump --db databaseName --out /backup/directory
    
  • Restore Database
    mongorestore /backup/directory
    
  • Export Collection
    mongoexport --collection=collectionName --db=databaseName --out=/export/path/file.json
    
  • Import Collection
    mongoimport --collection=collectionName --db=databaseName --file=/import/path/file.json
    

Connect to MongoDB

  • Connect via Mongo Shell
    mongo --host hostName --port portNumber -u userName -p password --authenticationDatabase admin
    
  • Connect via URI
    const MongoClient = require('mongodb').MongoClient;
    const uri = "mongodb://username:password@host:port/database";
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
    client.connect(err => {
      const collection = client.db("database").collection("collectionName");
      // perform actions on the collection object
      client.close();
    });
    

Transactions in MongoDB

In MongoDB, multi-document transactions are supported for replica sets. Transactions allow you to perform multiple operations on multiple documents in a consistent manner. Here's the syntax and an example of how to use transactions in MongoDB.

session.startTransaction();

try {
   // Perform multiple operations
   db.collection1.insertOne({ field: value });
   db.collection2.updateOne({ filter }, { $set: { field: value } });

   // If everything is successful, commit the transaction
   session.commitTransaction();
} catch (error) {
   // If any operation fails, abort the transaction
   session.abortTransaction();
   print("Transaction aborted:", error);
}

Example

Suppose we have two collections: customers and orders. We want to update the status of an order and decrease the available quantity of a product in an atomic operation. Here's how you can do it with a transaction:

session.startTransaction();

try {
   // Update order status
   db.orders.updateOne(
      { _id: orderId },
      { $set: { status: "shipped" } }
   );

   // Decrement product quantity
   db.products.updateOne(
      { _id: productId },
      { $inc: { quantity: -1 } }
   );

   // If everything is successful, commit the transaction
   session.commitTransaction();
   print("Transaction committed successfully!");
} catch (error) {
   // If any operation fails, abort the transaction
   session.abortTransaction();
   print("Transaction aborted:", error);
}

In this example, if either the update of the order status or the decrement of the product quantity fails, the entire transaction will be aborted, ensuring data consistency.

Tips

  • Use explain(): To understand query performance.
    db.collectionName.find({ key: "value" }).explain("executionStats")
    
  • Avoid Using eval(): For security reasons, avoid using db. eval().
  • Use bulkWrite(): For performing multiple write operations in a single batch.

Conclusion

This MongoDB cheat sheet provides a quick reference for essential commands and operations commonly used in MongoDB development. By familiarizing yourself with these commands, you can streamline your MongoDB workflow and efficiently manage your databases.


Similar Articles