MongoDB Cheatsheet

Deepak Ranolia
6 min readMay 19, 2024

--

MongoDB is a powerful and flexible NoSQL database, widely adopted for its scalability and ease of use. Whether you are just starting out or are an experienced database administrator, this comprehensive MongoDB cheat sheet is designed to help you navigate through the essential commands and operations. Organized into four proficiency levels — beginner, intermediate, advanced, and expert — each section provides 10 practical examples with concise descriptions. From basic CRUD operations to complex aggregation pipelines and advanced indexing strategies, this cheat sheet serves as a handy reference for developers and database administrators looking to efficiently manage and manipulate their data in MongoDB. Whether you’re building your first application or optimizing a large-scale system, this guide will enhance your MongoDB skills and improve your workflow.

The Beginner Level introduces the basic concepts and commands of MongoDB, focusing on essential CRUD operations. This section is perfect for those new to MongoDB, providing a solid foundation to build upon. Learn how to create, read, update, and delete documents in a MongoDB collection.

1Connect to MongoDB:
Connect to a MongoDB instance running locally.

const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();

2Create a Database:
Create or select a database named ‘myDatabase’.

const db = client.db('myDatabase');

3Create a Collection:
Create or select a collection named ‘myCollection’.

const collection = db.collection('myCollection');

4Insert a Document:
Insert a single document into a collection.

await collection.insertOne({ name: 'John Doe', age: 30 });

5Insert Multiple Documents:
Insert multiple documents into a collection.

await collection.insertMany([
{ name: 'Jane Doe', age: 25 },
{ name: 'Alice', age: 28 }
]);

6Find a Document:
Find a single document in a collection.

const document = await collection.findOne({ name: 'John Doe' });

7Find Multiple Documents:
Find all documents with age greater than or equal to 25.

const documents = await collection.find({ age: { $gte: 25 } }).toArray();

8Update a Document:
Update the age of ‘John Doe’ to 31.

await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });

9Delete a Document:
Delete the document with the name ‘John Doe’.

await collection.deleteOne({ name: 'John Doe' });

10Count Documents:
Count the number of documents in a collection.

const count = await collection.countDocuments();

The Intermediate Level delves deeper into MongoDB’s capabilities, covering more complex queries and indexing techniques. This section helps you understand how to optimize your database performance and execute more sophisticated queries. Get comfortable with sorting, filtering, and aggregation operations.

11Create an Index:
Create an ascending index on the ‘name’ field.

await collection.createIndex({ name: 1 });

12Unique Index:
Create a unique index on the ‘email’ field.

await collection.createIndex({ email: 1 }, { unique: true });

13Aggregation Pipeline:
Use aggregation to group documents by age and count them.

const result = await collection.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: '$age', count: { $sum: 1 } } }
]).toArray();

14Update Multiple Documents:
Update the status of all documents where age is less than 30.

await collection.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: 'young' } }
);

15Delete Multiple Documents:
Delete all documents where age is greater than or equal to 30.

await collection.deleteMany({ age: { $gte: 30 } });

16Text Search:
Perform a text search on the ‘name’ field.

await collection.createIndex({ name: 'text' });
const results = await collection.find({ $text: { $search: 'John' } }).toArray();

17Projection:
Retrieve only the ‘name’ and ‘age’ fields of documents.

const documents = await collection.find({}, { projection: { name: 1, age: 1 } }).toArray();

18Sort Documents:
Sort documents by age in descending order.

const documents = await collection.find().sort({ age: -1 }).toArray();

19Skip and Limit:
Skip the first 10 documents and limit the result to 5 documents.

const documents = await collection.find().skip(10).limit(5).toArray();

20Find and Modify:
Find a document and update it, returning the modified document.

const result = await collection.findOneAndUpdate(
{ name: 'Alice' },
{ $set: { age: 29 } },
{ returnOriginal: false }
);

The Advanced Level explores MongoDB’s powerful aggregation framework and its application in data analysis. You’ll learn how to create pipelines to transform and analyze data efficiently. This section is ideal for those looking to leverage MongoDB for detailed and large-scale data processing.

21Update with Upsert:
Update a document or insert it if it doesn’t exist (upsert).

await collection.updateOne(
{ name: 'Bob' },
{ $set: { age: 32 } },
{ upsert: true }
);

22Array Update Operations:
Add an item to an array field.

await collection.updateOne(
{ name: 'Jane Doe' },
{ $push: { hobbies: 'reading' } } );

23Array Filtered Update:
Update a specific element in an array that matches a condition.

await collection.updateOne(
{ name: 'Jane Doe', 'hobbies': 'reading' },
{ $set: { 'hobbies.$': 'traveling' } }
);

24Rename a Field:
Rename a field in all documents.

await collection.updateMany({}, { $rename: { 'oldName': 'newName' } });

25Bulk Write Operations:
Perform multiple write operations in bulk.

const bulkOps = [
{ insertOne: { document: { name: 'Alice', age: 28 } } },
{ updateOne: { filter: { name: 'Bob' }, update: { $set: { age: 32 } } } },
{ deleteOne: { filter: { name: 'John Doe' } } } ];

await collection.bulkWrite(bulkOps);

26Aggregation with Lookup:
Perform a join between two collections using aggregation lookup.

const result = await collection.aggregate([
{ $match: { name: 'Alice' } },
{ $lookup: {
from: 'otherCollection',
localField: 'name',
foreignField: 'name',
as: 'relatedData'
}}
]).toArray();

27Change Streams:
Monitor real-time changes to a collection.

const changeStream = collection.watch();
changeStream.on('change', (change) => {
console.log('Document changed:', change);
});

28Geospatial Query:
Perform a geospatial query to find documents near a point.

await collection.createIndex({ location: '2dsphere' });
const results = await collection.find({
location: {
$near: {
$geometry: { type: 'Point', coordinates: [ -73.9667, 40.78 ] },
$maxDistance: 1000
}
} }).toArray();

29TTL Index:
Create a TTL (Time-To-Live) index to automatically delete documents after a certain period.

await collection.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
);

30Partial Index:
Create an index on documents that match a specific condition.

await collection.createIndex(
{ age: 1 },
{ partialFilterExpression: { age: { $gt: 21 } } }
);

The Expert Level covers high-level MongoDB features such as sharding, replication, and advanced indexing. This section is designed for seasoned MongoDB users who need to manage large-scale deployments and ensure high availability. Master these techniques to maintain and optimize complex MongoDB environments.

31Sharding a Collection:
Enable sharding on a database and shard a collection.

await client.db('admin').command({
enableSharding: 'myDatabase'
});
await client.db('myDatabase').command({
shardCollection: 'myDatabase.myCollection',
key: { _id: 1 }
});

32Transactions:
Perform multiple operations in a transaction.

const session = client.startSession();
session.startTransaction();
try {
await collection.updateOne({ name: 'John' }, { $set: { age: 31 } }, { session });
await collection.updateOne({ name: 'Jane' }, { $set: { age: 26 } }, { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
} finally {
session.endSession();
}

33Faceted Search:
Perform a faceted search to get different views of the data.

const result = await collection.aggregate([
{ $match: { status: 'A' } },
{
$facet: {
price: [{ $bucket: { groupBy: '$price', boundaries: [ 0, 100, 200, 300 ] } }],
quantity: [{ $bucket: { groupBy: '$quantity', boundaries: [ 0, 50, 100 ] } }]
}
} ]).toArray();

34GridFS File Upload:
Upload a file to MongoDB using GridFS.

const bucket = new mongodb.GridFSBucket(db);
fs.createReadStream('file.txt').pipe(bucket.openUploadStream('file.txt'));

35GridFS File Download:
Download a file from MongoDB using GridFS.

bucket.openDownloadStreamByName('file.txt').pipe(fs.createWriteStream('file_downloaded.txt'));

36$graphLookup:
Perform a recursive search in a collection using $graphLookup.

const result = await collection.aggregate([
{
$graphLookup: {
from: 'employees',
startWith: '$managerId',
connectFromField: 'managerId',
connectToField: '_id',
as: 'reportingHierarchy'
}
}
]).toArray();

37Creating a View:
Create a view on a collection.

await db.createCollection('activeUsers', {
viewOn: 'users',
pipeline: [{ $match: { status: 'active' } }]
});

38Encrypted Fields:
Encrypt fields using MongoDB Client-Side Field Level Encryption.

const clientEncryption = new ClientEncryption(client, { keyVaultNamespace: 'encryption.__keyVault', kmsProviders });
const encryptedField = await clientEncryption.encrypt('sensitiveData', { algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' });

39$out Stage in Aggregation:
Write the result of an aggregation pipeline to a new collection.

await collection.aggregate([
{ $match: { status: 'active' } },
{ $out: 'activeUsers' } ]).toArray();

40Hidden Index:
Create a hidden index that can be used for testing without affecting query plans.

await collection.createIndex({ age: 1 }, { hidden: true });

This MongoDB cheat sheet provides a comprehensive guide to mastering MongoDB, from basic CRUD operations to advanced database management techniques. By progressing through the beginner, intermediate, advanced, and expert levels, you will gain a thorough understanding of MongoDB’s capabilities and best practices. Whether you are developing a simple application or managing a complex system, this cheat sheet is your go-to resource for efficient MongoDB operations.

--

--

Deepak Ranolia

Strong technical skills, such as Coding, Software Engineering, Product Management & Finance. Talk about finance, technology & life https://rb.gy/9tod91