DEV Community

Cover image for Master MongoDB: Comprehensive Cheat Sheet for Developers
Vishnu Satheesh
Vishnu Satheesh

Posted on • Updated on

Master MongoDB: Comprehensive Cheat Sheet for Developers

In today's world of data, MongoDB stands out as a top choice among NoSQL databases, thanks to its incredible flexibility. But truly grasping its ins and outs requires more than just scratching the surface.
This blog is here to help you unlock MongoDB's power, focusing on the key queries every developer needs to know. We'll cover everything from basic commands like creating and deleting databases to more advanced tasks like adding, searching, updating, and removing data.

Join us as we dive into the essential commands that make MongoDB a breeze for developers to use effectively.

Show All Databases

The show dbs command in MongoDB succinctly lists all available databases on the current MongoDB server, aiding developers and administrators in gaining a comprehensive overview of the database environment.

show dbs
Enter fullscreen mode Exit fullscreen mode

Show Current Database

The db command in MongoDB is used to reference the current or active database within the MongoDB shell. When invoked without any parameters, it simply returns the name of the current database, providing developers and administrators with quick confirmation of the database they are currently working with.

db
Enter fullscreen mode Exit fullscreen mode

Create Or Switch Database

The use command in MongoDB is used to create or switch to a specific database. If the specified database already exists, MongoDB will switch to that database. If the specified database does not exist, MongoDB will create it and then switch to it.

use <databaseName>
Enter fullscreen mode Exit fullscreen mode

Example:

> use myDatabase
switched to db myDatabase
Enter fullscreen mode Exit fullscreen mode

Drop

The "drop" command in MongoDB is used to remove a specific database or collection from the MongoDB server. When dropping a database, all collections within that database are also deleted. Similarly, dropping a collection removes all documents within that collection.
Dropping a database:

use <databaseName>
db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Dropping a collection:

db.<collectionName>.drop()
Enter fullscreen mode Exit fullscreen mode

Example of dropping a database:

> use myDatabase
switched to db myDatabase
> db.dropDatabase()
{ "dropped": "myDatabase", "ok": 1 }
Enter fullscreen mode Exit fullscreen mode

Example of dropping a collection:

> db.myCollection.drop()
true
Enter fullscreen mode Exit fullscreen mode

Create Collection

In MongoDB, the createCollection command is used to explicitly create a new collection within a database. This command allows developers to specify various options for the new collection, such as setting validation rules, defining indexes, and configuring storage options.

db.createCollection(<name>, options)
Enter fullscreen mode Exit fullscreen mode

Example:

db.createCollection(
    "logs",
    {
        capped: true, // Create a capped collection
        size: 1048576, // Set the maximum size of the collection to 1 MB
        max: 1000, // Set the maximum number of documents in the collection to 1000
        timeseries: {
            timeField: "timestamp", // Define the time field for time series collection
            metaField: "meta", // Define the meta field for time series collection
            granularity: "seconds", // Set the granularity of the time series data
            bucketMaxSpanSeconds: 3600, // Set the maximum span of each bucket to 1 hour
            bucketRoundingSeconds: 60 // Round bucket boundaries to nearest minute
        },
        expireAfterSeconds: 604800, // Expire documents after 7 days
        validationLevel: "strict", // Set validation level to strict
        validationAction: "error", // Set validation action to error
        validator: {
            $jsonSchema: {
                bsonType: "object",
                required: ["message", "level"],
                properties: {
                    message: {
                        bsonType: "string",
                        description: "must be a string and is required"
                    },
                    level: {
                        enum: ["info", "warning", "error"],
                        description: "must be one of: 'info', 'warning', 'error' and is required"
                    },
                    timestamp: {
                        bsonType: "date",
                        description: "must be a date"
                    }
                }
            }
        }
    }
)

Enter fullscreen mode Exit fullscreen mode

Show Collections

The show collections command in MongoDB is used to display a list of all collections in the current database. It provides a quick overview of the collections available for querying and manipulation.

show collections
Enter fullscreen mode Exit fullscreen mode

Example

> show collections
myCollection1
myCollection2
system.indexes
Enter fullscreen mode Exit fullscreen mode

Insert Document

To insert a document (row) into a collection in MongoDB, you can use the insertOne() method to insert a single document or the insertMany() method to insert multiple documents at once.

Syntax for inserting a single document:

db.<collectionName>.insertOne({ <documentData> })
Enter fullscreen mode Exit fullscreen mode

Syntax for inserting multiple documents:

db.<collectionName>.insertMany([ { <document1Data> }, { <document2Data> }, ... ])
Enter fullscreen mode Exit fullscreen mode

Example of inserting a single document:

db.myCollection.insertOne({ name: "John", age: 30, city: "New York" })
Enter fullscreen mode Exit fullscreen mode

Example of inserting multiple documents:

db.myCollection.insertMany([
    { name: "Alice", age: 25, city: "Los Angeles" },
    { name: "Bob", age: 35, city: "Chicago" },
    { name: "Emily", age: 28, city: "San Francisco" }
])
Enter fullscreen mode Exit fullscreen mode

Get All Rows

To retrieve all documents (rows) from a collection in MongoDB, you can use the find() method without any query criteria. This method returns a cursor that allows you to iterate over all documents in the collection.

db.<collectionName>.find()
Enter fullscreen mode Exit fullscreen mode

Example

db.myCollection.find()
Enter fullscreen mode Exit fullscreen mode

Get All Rows Formatted

To retrieve all documents (rows) from a collection in MongoDB in a formatted manner, you can use the pretty() method along with the find() method. The pretty() method formats the output to be more readable.

db.<collectionName>.find().pretty()
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find().pretty()
Enter fullscreen mode Exit fullscreen mode

Find Rows

To find specific documents (rows) within a collection in MongoDB, you can use the find() method with query criteria. This allows you to retrieve documents that match certain conditions.

db.<collectionName>.find(<query>)
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find({ name: "John" })
Enter fullscreen mode Exit fullscreen mode

Sort Rows

To sort the documents (rows) returned by a query in MongoDB, you can use the sort() method along with the find() method. This allows you to specify the field(s) by which the documents should be sorted and the sorting order.

db.<collectionName>.find().sort(<sortCriteria>)
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find().sort({ name: 1 })
Enter fullscreen mode Exit fullscreen mode

Count Rows

To count the number of documents (rows) in a collection in MongoDB, you can use the countDocuments() method. This method returns the count of documents that match the specified query criteria.

db.<collectionName>.countDocuments(<query>)
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.countDocuments()
Enter fullscreen mode Exit fullscreen mode

Limit Rows

To limit the number of documents (rows) returned by a query in MongoDB, you can use the limit() method along with the find() method. This allows you to specify the maximum number of documents to retrieve.

db.<collectionName>.find().limit(<limitValue>)
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find().limit(10)
Enter fullscreen mode Exit fullscreen mode

Chaining

Chaining in MongoDB refers to the process of combining multiple operations or methods together in a single query. This allows you to perform various operations sequentially on the data returned by a query.

For example, you can chain methods like find(), sort(), limit(), and skip() together to create more complex queries.

db.<collectionName>.find(<query>).sort(<sortCriteria>).limit(<limitValue>)

Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find({ status: "active" }).sort({ createdAt: -1 }).limit(10)
Enter fullscreen mode Exit fullscreen mode

Find One Row

To retrieve a single document (row) from a collection in MongoDB, you can use the findOne() method. This method returns the first document that matches the specified query criteria.

db.<collectionName>.findOne(<query>)
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.findOne({ name: "John" })
Enter fullscreen mode Exit fullscreen mode

Foreach

In MongoDB, the forEach() method is used to iterate over the documents in a cursor returned by a query and perform a specified operation for each document.

db.collection.find().forEach( <function> )
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find().forEach(function(doc) {
    print("Name: " + doc.name + ", Age: " + doc.age);
})
Enter fullscreen mode Exit fullscreen mode

Find Specific Fields

To retrieve specific fields from documents in a collection in MongoDB, you can use the find() method along with projection to specify which fields you want to include or exclude in the returned documents.

db.<collectionName>.find(<query>, { field1: 1, field2: 1, ... })
Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.find({ title:'Post one' }, {
title: 1,
author: 1
})
Enter fullscreen mode Exit fullscreen mode

Update Row

To update one or more documents in a collection in MongoDB, you can use the updateOne() method to update a single document or the updateMany() method to update multiple documents that match the specified query criteria.
Syntax for updating a single document:

db.<collectionName>.updateOne(<filter>, <update>, <options>)
Enter fullscreen mode Exit fullscreen mode

Syntax for updating multiple documents:

db.<collectionName>.updateMany(<filter>, <update>, <options>)
Enter fullscreen mode Exit fullscreen mode

Example of updating a single document:

db.myCollection.updateOne({ name: "John" }, { $set: { age: 35 } })
Enter fullscreen mode Exit fullscreen mode

Example of updating multiple documents:

db.myCollection.updateMany({ status: "active" }, { $set: { status: "inactive" } })
Enter fullscreen mode Exit fullscreen mode

Rename field

To rename a field in documents within a collection in MongoDB, you can use the $rename update operator along with the updateMany() method to update multiple documents or updateOne() method to update a single document.

db.<collectionName>.updateMany(<filter>, { $rename: { <oldFieldName>: <newFieldName> } })

Enter fullscreen mode Exit fullscreen mode

Example:

db.myCollection.updateMany({}, { $rename: { "oldField": "newField" } })
Enter fullscreen mode Exit fullscreen mode

Delete row

To delete one or more documents from a collection in MongoDB, you can use the deleteOne() method to delete a single document or the deleteMany() method to delete multiple documents that match the specified query criteria.

Syntax for deleting a single document:

db.<collectionName>.deleteOne(<filter>)
Enter fullscreen mode Exit fullscreen mode

Syntax for deleting multiple documents:

db.<collectionName>.deleteMany(<filter>)
Enter fullscreen mode Exit fullscreen mode

Example of deleting a single document:

db.myCollection.deleteOne({ name: "John" })
Enter fullscreen mode Exit fullscreen mode

Example of deleting multiple documents:

db.myCollection.deleteMany({ status: "inactive" })
Enter fullscreen mode Exit fullscreen mode

Find By Element in Array

In MongoDB, you can query documents based on elements within an array using the $elemMatch operator or array operators such as $in, $all, $elemMatch, etc., depending on your specific requirements.

db.collectionName.find({ fieldName: { $elemMatch: { <queryCondition> } } })

Enter fullscreen mode Exit fullscreen mode

Example:

db.books.find({ authors: { $elemMatch: { name: "John" } } })
Enter fullscreen mode Exit fullscreen mode

Add Index

In MongoDB, you can add indexes to fields in your collection to improve query performance. Indexes allow MongoDB to efficiently locate documents based on the indexed fields.

To add an index to a field in MongoDB, you can use the createIndex() method.

db.collectionName.createIndex({ fieldName: 1 })
Enter fullscreen mode Exit fullscreen mode

Example:

db.books.createIndex({ title: 1 })
Enter fullscreen mode Exit fullscreen mode

Text Search

In MongoDB, you can perform text searches using the $text operator along with the $search operator. Text searches allow you to search for documents that contain specific words or phrases in indexed fields.

Before performing text searches, you need to ensure that at least one field in your collection is indexed with the text index. You can create a text index using the createIndex() method with the text index type.

Syntax to create a text index:

db.collectionName.createIndex({ fieldName: "text" })
Enter fullscreen mode Exit fullscreen mode

Syntax for text search:

db.collectionName.find({ $text: { $search: "searchQuery" } })
Enter fullscreen mode Exit fullscreen mode

Example:

db.books.find({ $text: { $search: "MongoDB" } })
Enter fullscreen mode Exit fullscreen mode

Greater & Less Than

In MongoDB, you can perform greater than ($gt), greater than or equal to ($gte), less than ($lt), and less than or equal to ($lte) comparisons to query documents based on numeric or date values.
Syntax for greater than:

db.collectionName.find({ fieldName: { $gt: value } })
Enter fullscreen mode Exit fullscreen mode

Syntax for greater than or equal to:

db.collectionName.find({ fieldName: { $gte: value } })
Enter fullscreen mode Exit fullscreen mode

Syntax for less than:

db.collectionName.find({ fieldName: { $lt: value } })
Enter fullscreen mode Exit fullscreen mode

Syntax for less than or equal to:

db.collectionName.find({ fieldName: { $lte: value } })
Enter fullscreen mode Exit fullscreen mode

Example:

// Find books priced $50 or higher
db.books.find({ price: { $gte: 50 } })

// Find books priced less than $30
db.books.find({ price: { $lt: 30 } })

// Find books priced $30 or less
db.books.find({ price: { $lte: 30 } })
Enter fullscreen mode Exit fullscreen mode

Mastering the querying methods discussed in this article is essential for efficiently retrieving data from MongoDB collections based on specific criteria.

By familiarizing yourself with these fundamental querying techniques such as finding documents by field values, performing text searches, and using comparison operators for numeric or date values, you can effectively filter and retrieve relevant information from your MongoDB databases. 🚀

I hope you found this article informative and helpful in enhancing your MongoDB querying skills! If you enjoyed it, don't hesitate to leave a comment and share your thoughts. Thank you! 😊

Buy Me A Coffee

Top comments (0)