Table of contents
1.
Introduction
2.
What is MongoDB Database?
3.
1. db.adminCommand(cmd)
3.1.
Syntax
3.2.
Example
4.
2. db.aggregate()
4.1.
Syntax:
4.2.
Example:
5.
3. db.cloneDatabase("hostname")
5.1.
Syntax
5.2.
Example
6.
4. db.commandHelp(command)
6.1.
Syntax
6.2.
Example
7.
5. db.createCollection(name, options)
7.1.
Syntax
7.2.
Example
8.
6. db.createView()
8.1.
Syntax
8.2.
Example
9.
7. db.dropDatabase(<writeConcern>)
9.1.
Syntax
9.2.
Example
10.
8. db.getLogComponents()
10.1.
Syntax
10.2.
Example
11.
Frequently Asked Questions
11.1.
What is the purpose of db.adminCommand()?
11.2.
How is db.aggregate() different from normal queries?
11.3.
Can I undo a db.dropDatabase() command?
12.
Conclusion
Last Updated: Jan 5, 2025
Easy

MongoDB Commands

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

MongoDB is a powerful NoSQL database that is widely used for handling large datasets and dynamic applications. As a college student or a budding software engineer, learning MongoDB commands is essential for building and managing databases efficiently. 

MongoDB Commands

This article will discuss some of the key MongoDB commands, their syntax, and how they function, with examples that you can run and practice.

What is MongoDB Database?

MongoDB is a type of database that falls under the category of NoSQL databases. Unlike traditional SQL databases like MySQL or PostgreSQL, which store data in tables with rows & columns, MongoDB stores data in a document format. These documents are similar to JSON (JavaScript Object Notation) objects, making them easy to read & work with.  

Let’s take an example of how data looks in MongoDB:  

{
  "_id": "12345",
  "name": "John Doe",
  "age": 25,
  "email": "john.doe@example.com",
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}


In this example, each piece of data is stored as a key-value pair. The `_id` field is unique for every document & acts as the primary key. MongoDB groups these documents into collections, which are similar to tables in SQL databases. For instance, you might have a collection called `users` to store all user-related data.  

One of the biggest advantages of MongoDB is its flexibility. You don’t need to define a fixed structure for your data before storing it. This means you can store different types of data in the same collection without worrying about rigid schemas. For example, one document in the `users` collection might have an `age` field, while another might not.  

Note: MongoDB is also highly scalable, meaning it can handle large amounts of data & high traffic without slowing down. This makes it a great choice for modern applications like social media platforms, e-commerce websites, & mobile apps.  

1. db.adminCommand(cmd)

The db.adminCommand() method is used to execute administrative operations in MongoDB. It allows you to send administrative commands to the database.

Syntax

db.adminCommand({ command: <command> })

Example

db.adminCommand({ listDatabases: 1 })

Explanation:

The above command lists all the databases available in your MongoDB instance. When you run it, you will see an output like this:

Output:

{
    "databases": [
        { "name": "admin", "sizeOnDisk": 4096 },
        { "name": "test", "sizeOnDisk": 8192 }
    ],
    "totalSize": 12288,
    "ok": 1
}


This is a useful command for checking the databases and their sizes.

2. db.aggregate()

The db.aggregate() command is used for performing advanced data processing and aggregation. It processes data in stages like filtering, grouping, and transforming.

Syntax:

db.collection.aggregate([ pipeline ], options)

Example:

db.orders.aggregate([
    { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }
])


Explanation:

In this example, we are grouping the orders collection by customerId and calculating the total amount of orders for each customer.

Output:

[
    { "_id": 1, "totalAmount": 250 },
    { "_id": 2, "totalAmount": 500 }
]


The aggregation pipeline is a powerful tool to manipulate and analyze data in MongoDB.

3. db.cloneDatabase("hostname")

The db.cloneDatabase() command is used to copy data from one MongoDB instance to another.

Syntax

db.cloneDatabase("hostname")

Example

db.cloneDatabase("192.168.1.100")


Explanation:

This command copies the database from the server with the IP address 192.168.1.100. Note that this command is deprecated in newer versions of MongoDB. Always refer to the official documentation for updates.

4. db.commandHelp(command)

The db.commandHelp() command provides a description of a specific database command.

Syntax

db.commandHelp("<command>")

Example

db.commandHelp("aggregate")


Explanation:

Running this command displays detailed help and syntax for the aggregate command. This is particularly useful when you’re unsure about a command’s options and usage.

5. db.createCollection(name, options)

The db.createCollection() command creates a new collection with optional configurations.

Syntax

db.createCollection("name", options)

Example

db.createCollection("students", { capped: true, size: 5000 })


Explanation:

Here, a new collection named students is created. The capped option limits the collection size to 5,000 bytes. This is helpful when you need to manage storage for specific collections.

Output:

{ "ok": 1 }

6. db.createView()

The db.createView() command creates a read-only view of data based on an aggregation pipeline.

Syntax

db.createView("viewName", "sourceCollection", [ pipeline ])

Example

db.createView("highScorers", "students", [
    { $match: { score: { $gt: 90 } } }
])


Explanation:

This command creates a view named highScorers that includes students with scores greater than 90. Views are helpful when you need to present data in a specific format without altering the original collection.

7. db.dropDatabase(<writeConcern>)

The db.dropDatabase() command deletes the current database, including all its collections and documents.

Syntax

db.dropDatabase({ writeConcern })

Example

db.dropDatabase()


Explanation:

When you run this command, the current database is removed permanently. Be cautious when using it.


Output:

{ "dropped": "test", "ok": 1 }

8. db.getLogComponents()

The db.getLogComponents() command retrieves the current logging settings for the database.

Syntax

db.getLogComponents()

Example

db.getLogComponents()


Explanation:

This command displays the logging levels for different components of MongoDB. The output might look like this:

Output:

{
    "verbosity": 0,
    "components": {
        "accessControl": { "verbosity": -1 },
        "command": { "verbosity": -1 },
        ...
    }
}


This is useful for debugging and optimizing your database operations.

Frequently Asked Questions

What is the purpose of db.adminCommand()?

The db.adminCommand() is used for executing administrative commands, such as checking database statuses or managing system configurations.

How is db.aggregate() different from normal queries?

The db.aggregate() command allows for advanced data processing using multiple stages, like grouping and filtering, which is not possible with simple queries.

Can I undo a db.dropDatabase() command?

No, the db.dropDatabase() command is irreversible. Always double-check before running it.

Conclusion

In this article, we discussed some essential MongoDB commands, their syntax, and use cases. From administrative operations with db.adminCommand() to data aggregation with db.aggregate(), each command serves a specific purpose in database management. Practice these commands regularly to build a strong foundation in MongoDB. These commands are not only useful for managing data but also play a significant role in interview preparation and real-world applications.

You can also check out our other blogs on Code360.

Live masterclass