MongoDB Basic Commands

Learn via video courses
Topics Covered

Overview

MongoDB offers a range of database commands that enable you to perform operations on databases within a MongoDB instance. These MongoDB commands are used for managing databases, creating, deleting, and modifying collections, executing administrative tasks, and performing advanced data manipulation operations.

Importance of MongoDB Commands

MongoDB commands are important as they are essential for managing and interacting with a MongoDB database. MongoDB commands are essential for the following reasons:

  • Data manipulation: Basic MongoDB commands allow users to insert, update, and delete data from the database. These MongoDB commands can be used to manage data efficiently and accurately.
  • Querying data: With basic MongoDB commands, users can query the database for specific information, filter data based on certain criteria, and sort data according to user-defined preferences.
  • Index creation: Basic MongoDB commands enable the creation of indexes on collections, which can significantly improve query performance by making it easier and faster to find the desired data.
  • Administration and maintenance: Basic MongoDB commands can be used to manage user access and permissions, monitor database performance, and perform backups and restores.
  • Automation: Basic MongoDB commands can be automated using scripts and tools, making it possible to execute complex tasks quickly and efficiently.

MongoDB Database Commands

db.runCommand(cmd)

The db.runCommand(cmd) is a MongoDB shell method that runs only against the current database however some commands are only applicable in the context of the admin database.

Syntax:

  • cmd: The name of the administrative command to be executed. This is a required field and should be a string representing the name of the command.
  • Additional command options: You can pass additional options as key-value pairs in the object. The options depend on the specific administrative command being executed.

db.adminCommand(cmd)

The db.adminCommand() command in MongoDB lets you execute commands against the admin database, independent of the database context in which the function is used.

MongoDB User Commands

MongoDB provides various user-related commands that allow administrators to manage user accounts, roles, and privileges. These commands are used to create, modify, and delete users, as well as assign roles and permissions to them.

Aggregation Commands

MongoDB provides powerful aggregation commands that allow users to perform complex data analysis and transformations on their collections.

Before understanding the commands let's consider a collection called "orders" that contains documents with the following structure:

1. aggregate()

This MongoDB command is used to perform aggregation operations on a collection.

Syntax:

Example Calculate the total revenue for each product using db.runCommand(aggregate)

Output:

2. count()

This MongoDB command is used to count the number of documents in a collection that match a query.

Syntax:

Example

Count the total number of orders using db.runCommand(count)

Output:

3. distinct()

This MongoDB command is used to find the distinct values for a field in a collection.

Syntax:

Example

Retrieve all distinct products using db.runCommand(distinct)

Output:

4. mapReduce()

This MongoDB command is used to perform complex data analysis operations on a collection using map-reduce.

Syntax:

Example

Calculate the total revenue for each product using map-reduce and db.runCommand(mapReduce)

Output:

Query and Write Operation Commands

Write Operations

Write operations in MongoDB are used to perform various write operations on the database, such as inserting, updating, and deleting documents. These commands allow you to manipulate data in MongoDB collections.

Before understanding the Basic MongoDB commands let's consider a collection called "users" that contains documents with the following structure:

1. delete()

We can use the delete command to remove documents from a collection, with the option to specify multiple deletions in a single command. However, it's important to remember that this command does not apply to capped collections. The MongoDB removal method internally utilizes the delete command.

Syntax:

Example

Delete a user by ID using db.runCommand(delete)

Output:

2. update()

This MongoDB basic command is used to modify documents in a collection, allowing for multiple update statements. This command is utilized by the MongoDB drivers' update method to make changes to documents.

Syntax:

Example

Update a user's age using db.runCommand(update)

Output:

3. insert()

The insert method in MongoDB is utilized to add one or more documents to a collection, and it returns a document that contains the status of all inputs. This method internally employs the insert command provided by MongoDB.

Syntax:

Example

Insert a new user using db.runCommand(insert)

Output:

Query Operations

Query operations in MongoDB are used to retrieve data from collections based on specified criteria.

4. findAndModify()

This MongoDB command is used to modify and return a single document at a time. By default, the returned document does not include the modifications made during the update. However, the new option can be used to return the modified document as well.

Syntax:

Example

Find and modify a user's age using db.runCommand(findAndModify)

Output:

5. find()

This basic MongoDB command is utilized to execute a query and retrieve the first set of results, along with the cursor ID which can be used to construct a cursor for further processing.

Syntax:

Example

Find all users using db.runCommand(find)

Output:

Database Operation Commands

Authentication Commands

Authentication commands in MongoDB are used to manage user authentication and authorization for accessing the database system. These commands allow you to create, manage, and authenticate users, as well as set up roles and privileges for controlling access to databases and collections.

1. authenticate command:

The authenticate command is used to authenticate a user with MongoDB. This MongoDB command takes a username and password as arguments, and if the username and password are correct, the user is authenticated.

Syntax:

2. getnonce command:

The getnonce command is used to retrieve a one-time password that can be used for authentication. This command is used as a security measure to prevent replay attacks.

3. logout command:

The logout command is used to terminate an authenticated session. This command invalidates the session and the user needs to re-authenticate to access the database.

Syntax:

User Management Commands

1. createUser()

The createUser() basic MongoDB command is used to create a new user with the specified username, password, and roles. Users in MongoDB are used for authentication and authorization purposes, allowing control over access to databases and collections.

Syntax:

Example

Output:

This creates a user with the username "myuser" and password "mypassword" in the "mydatabase" database, with the "readWrite" role.

2. dropUser()

The dropUser() basic MongoDB command is used to delete an existing user and all associated authentication credentials from the database. This command is typically used when a user is no longer needed or when it is necessary to revoke access for a user.

Syntax:

Example

Output:

This drops the user with the username "myuser", with a write concern of "majority" and a timeout of 5000 milliseconds. Note that the writeConcern option is optional and can be used to specify the level of write concern for the operation.

3. updateUser()

This basic MongoDB command is used to modify the roles and privileges of an existing user in MongoDB.

Syntax:

Example

Output:

This updates the password and roles for the user with the username "myuser" to "newpassword" and the "readWrite" role in the "mydatabase" database.

Role Management Commands

1. createRole

The createRole command in MongoDB is utilized to assign a role and define its advantages. The role is applied to the database on which the command is executed. In case the role already exists in the database, the command will return an error indicating a duplicate role.

Syntax:

2. dropRole

The dropRole command in MongoDB is used to delete a user-defined role from the database on which the command is executed.

Syntax:

3. updateRole

The update command modifies the user-defined role and must be executed on the role's database. This basic MongoDB command can completely replace the previous field value with a new value.

Syntax:

4. grantPrivilagesToRole

The grantPrivilagesToRole is a significant command used to add additional privileges to a user-defined role on the database where the command is executed.

Syntax:

5. rolesInfo

The rolesInfo command in MongoDB retrieves details about inheritance and privileges associated with specific roles, including both custom roles created by users and pre-defined roles. Additionally, this command can also retrieve information about all roles that are scoped to a particular database.

Syntax:

6. invalidateUserCache

The invalidateUserCache command in MongoDB clears the user information from the in-memory cache, including credentials and roles for each user, effectively invalidating the cache.

Syntax:

7. revokeRolesFromRole

The revokeRolesFromRole command in MongoDB removes the specified inherited roles from a role, effectively revoking those roles from the parent role.

Syntax:

Replication Commands

A MongoDB replica set is a group of Mongod processes that store the same data set. Replica sets are designed to provide redundancy and high availability, making them crucial for production deployments. This section covers an introduction to replication in MongoDB, including the components and architecture of replica sets. It also includes tutorials for various tasks related to managing replica sets.

1. replSetAbortPrimaryCatchUp command

The replSetAbortPrimaryCatchUp command in MongoDB is used to forcefully terminate the sync process on the specified primary member of the replica set, allowing it to complete the transition to becoming the primary member.

Syntax:

2. replSetInitiate command

The replSetInitiate MongoDB command is used to start the process of creating a new replica set.

Syntax:

3. replSetGetStatus command

The replSetGetStatus MongoDB command retrieves the status of the replica set as seen from the perspective of the server that executed the command. It is required to be executed on the admin database.

Syntax:

4. replSetReconfig command

The replSetReconfig administrative MongoDB command is used to modify the configuration of an existing replica set. It allows you to add or remove members and modify options on existing members. This command must be executed on the admin database of the primary replica set member.

Syntax:

Sharding Commands

Sharding is a strategy utilized by MongoDB to spread data across multiple machines, enabling effective management of extensive data sets and high throughput operations.

sharding commands

1. enableSharding

The enableSharding command is used to explicitly create a database in MongoDB.

Syntax:

2. balancerStatus

The balancerStatus MongoDB command retrieves a document that provides details about the current status of the balancer.

Syntax:

3. addShard

The addShard MongoDB command is used to include a replica set shard in a sharded cluster.

Syntax:

4. listShards

The listShards command is a MongoDB shell command that is used to retrieve information about the shards in a MongoDB sharded cluster. It allows you to obtain details about the status and configuration of the individual shards that make up the sharded cluster.

Syntax:

5. shardingState

The shardingState command is an administrative command in MongoDB that provides information about whether a mongod instance is part of a sharded cluster.

Syntax:

Session Commands

Session commands in MongoDB are administrative commands that are used to manage sessions, which are client-side objects that represent a sequence of operations on a MongoDB server. Sessions are used to group operations into logical units and provide support for transactions, which allow for multiple operations to be executed as a single atomic transaction.

1. startSession

The startSession MongoDB command initiates a new logical session for a sequence of operations.

Syntax:

2. commitTransaction

The commitTransaction MongoDB command persistently stores the modifications made by the operations within a multi-document transaction and concludes the transaction.

Syntax:

3. abortTransaction

The abortTransaction command terminates a multi-document transaction and undoes any data modifications made by the operations within the transaction. This means that the transaction is terminated without persistently saving any of the changes made by the operations.

Syntax:

4. endSessions

The endSessions command invalidates the specified sessions, overriding the timeout period that sessions normally wait before expiring.

Syntax:

5. killSessions

The killSessions command is used in MongoDB to terminate specific sessions. When access control is enabled, this command only terminates sessions that are owned by the user who issued the command.

Syntax:

6. refreshSessions

The refreshSessions command in MongoDB is used to update the last use time of specified sessions, effectively extending the active state of those sessions.

Syntax:

Administration Commands

Administration commands in MongoDB are commands used for administrative tasks that involve managing the overall configuration, security, and performance of a MongoDB deployment. These commands are typically used by database administrators (DBAs) or privileged users with administrative privileges to manage and maintain MongoDB instances.

1. create

The create command is used to explicitly create a collection or view.

Syntax:

Example

Output:

2. drop

The drop command deletes an entire collection from a database.

Syntax:

Example

Output:

3. listDatabases

The listDatabases command displays a list of all databases that currently exist, along with basic statistics about each database.

Syntax:

4. createIndexes

The createIndexes command generates one or more indexes on a collection.

Syntax:

5. renameCollection

The renameCollection command in MongoDB is used to change the name of an existing collection. The collection names to be renamed should be provided in the form of a complete namespace, which includes the database name and the collection name, separated by a dot (e.g., <database>.<collection>).

Syntax:

Example

Output:

6. shutdown

The shutdown command in MongoDB is used to clean up all database resources and terminate the process. To execute the shutdown command, it must be issued against the admin database.

Syntax:

Diagnostic Commands

Diagnostic commands in MongoDB are administrative commands that provide information about the status, configuration, and performance of a MongoDB deployment. These commands are designed to help administrators and developers diagnose and troubleshoot issues related to MongoDB deployments, performance optimizations, and system monitoring.

1. dataSize

The dataSize command provides the size of the specified data in bytes.

Syntax:

2. explain

The explain command gives details about the execution of various commands such as aggregate, count, distinct, find, findAndModify, delete, mapReduce, and update.

Syntax:

3. listCommands

The listCommands command generates a comprehensive list of all the database commands that are implemented in the current instance of mongod or mongos.

Syntax:

4. validate

The validate command verifies the correctness of a collection's data and indexes and provides the results of the validation.

Syntax:

The validate command does not support views and will result in an error if executed against a view.

5. serverStatus

The serverStatus command retrieves a document that offers a summary of the current state of the database. This command is often used by monitoring applications to collect statistics about the instance at regular intervals.

Syntax:

Auditing Commands in MongoDB

Auditing in MongoDB involves the recording and monitoring of different activities within the database system, such as user authentication, authorization, and other operations. MongoDB offers built-in auditing capabilities that enable the capture of audit events and tracking of system changes.

logApplicationMessage

The logApplicationMessage command enables users to add a custom message to the audit log. When authorization is active, users must have the clusterAdmin role or roles that inherit from clusterAdmin to execute the command.

Syntax:

How to Use MongoDB Commands?

Install MongoDB Server: To download the latest version of MongoDB can be done using https://www.mongodb.org/downloads

Start MongoDB Server : Once MongoDB is installed, you need to start the MongoDB server. The process for starting the MongoDB server varies depending on your operating system. For example, on Windows, you can start the MongoDB server by running the mongod.exe executable. On Unix-based systems, you can start the MongoDB server by running the Mongod command in a terminal.

Connecting to MongoDB : To connect to a MongoDB server, you can use the Mongo command-line interface or a MongoDB client.

Use a Database : Once connected to MongoDB, you can select a database to work with using the use command. For example, to use a database named "mydb", you can run the following command in the Mongo shell:

Execute MongoDB Commands : Now, you can start executing MongoDB commands in the Mongo shell or any other MongoDB client.

FAQs

Q. What are some common options that can be passed as additional command options in the db.runCommand(cmd) command?

A. Some common options that can be passed as additional command options in the db.runCommand(cmd) command include writeConcern for specifying the level of write concern, comment for adding comments to the command, and explain for obtaining information on how MongoDB executes the command.

Q. Can I create custom commands in MongoDB?

A. Yes, MongoDB allows you to create custom commands using JavaScript. You can define custom commands as server-side JavaScript functions and execute them using the db.runCommand() method or by registering them with the MongoDB server as part of a custom script or module.

Q. How do I connect to a MongoDB server?

A. You can connect to a MongoDB server using the MongoDB shell or a MongoDB client driver. Here's how:

MongoDB Shell : Run mongo in the command prompt or terminal to launch the MongoDB shell and connect to the default MongoDB server running on localhost.

MongoDB Client Driver : Use the appropriate MongoDB client driver for your programming language (e.g., pymongo for Python, MongoDB for Node.js) and connect to the MongoDB server using the connection string or connection parameters.

MCQs

a. Which MongoDB command is used to modify and return a single document at a time?

i. delete() ii. update() iii. insert() iv. findAndModify()

v. Correct Answer: d. findAndModify()

b. What is the purpose of the getnonce command in MongoDB?

i. To create a new user with a specified username and password. ii. To retrieve a one-time password for authentication. iii. To terminate an authenticated session. iv. To modify the roles and privileges of an existing user.

v. Correct Answer: b. To retrieve a one-time password for authentication.

c. What is the purpose of the privileges field in the createRole command in MongoDB?

i. To specify the role to be created. ii. To define the actions allowed for a role. iii. To configure authentication restrictions for a role. iv. To specify the written concern for a role.

v.Correct Answer: b. To define the actions allowed for a role.