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

CRUD Operations

Advanced Operations

Indexing

Aggregation

Aggregation Pipeline

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

Replication and Sharding

Miscellaneous Operations

Connect to MongoDB

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

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.