Top MongoDB Commands You Need to Know

This article will discuss the most effective commands to use to help with MongoDB administration of the database.

We’ll begin by introducing the fundamental concepts of MongoDB. After that, I’ll teach you how to perform various administrative tasks using commands that can be used for:

  • Connecting
  • Databases, collections role, users and databases
  • Managing users
  • Checking logs
  • The management of the database
  • Gathering collection information
  • Naming collections
  • Ending an instance

Let’s get started!

(This post is part our MongoDB Guide. Make use of the menu on the right to navigate. )

MongoDB overview

MongoDB is a fast extremely scalable, platform-independent NoSQL databases. MongoDB uses concepts like Collections, Documents, and Databases:

  • Documents and collections are comparable to the row and table of the RDBMS database.
  • One MongoDB instance may contain several databases. It is an actual container for collections that has an exclusive file structure within the system.

A Collection is a collection composed of MongoDB documents. Collections are stored within databases and don’t have to adhere to an established schema, like traditional databases. So, the documents that are part of the same collection could contain distinct fields. MongoDB Documents are created using key-value pair.

Let’s look at how the traditional RDBMS terminology is related with MongoDB structure.

Database Management System Database Management SystemMongoDB
RowBSON document
ColumnBSON field
Primary crucialField _id (Primary key)In default MongoDB automatically generates a 12 bytes Hexadecimal code for each document.
JoinLinking and Embedding

Like all databases, MongoDB needs administration. This is where the administrative commands are involved. Let’s take a look.

Commands to connect to MongoDB

In the beginning, we must be aware of the best way to join the MongoDB database. Use the mongo command for connecting to the MongoDB database, and then use parameters such as host and port when needed.

  • mongo This command should be run in your localhost shell in order to access the database using the default port of 27017.
  • mongo / Set the host and database as parameters for connecting to a particular database.
  • mongo -host -port [options] This format is a way to define different options when connecting to the database. Visit the mongoman pages or help for more on all options available.

mongo host Port 27017 --verbose

mongo -host -port -authenticationDatabase -u -p

If authentication is enabled within your MongoDB configuration, then we will be able to provide the user’s details as well as the database used for authentication. This database contains the user’s details are stored, and it could be any database created to allow users to sign up. If you do not enter the password during the command the cmd will ask for it in the future.

mongo --port 27017 --authenticationDatabase "admin" -u "barryadmin" -p

MongoDB display command

Let’s look at how to look up objects within the MongoDB database. You can search for current databases collection, roles, and users by using show. “show” command.

View all databases

Show the dbs

Access collections within the database

show collections / db.getCollectionNames()

Access roles from the database

Play roles in shows

Access users from the database

display users / db.getUsers()

User management commands

A very critical administrative tasks is managing access rights for users. MongoDB offers this capability by using roles and users, and has built-in roles that allow for simple access control.

You must activate your “authentication” feature in the MongoDB configuration file to enable an access control function. Incorporate the following lines into the mongod.conf file, and then start MongoDB service. MongoDB service in order to update the modifications.


security: authorization: "enabled"

Create users

This CreateUser command lets us create users. Let’s create a new user for the database of vehicles that has only write and read permissions.


db.createUser( { user: , pwd: , roles: [ {role: , db: } ] } )


use vehicles db.createUser(  )


It is the passwordPromt() function will request the password while performing the createUser command. User creation occurs within the database called “vehicles” databases.

So, when we authenticate using this user, we must specify the “vehicles” database as the “authenticationDatabase”. Database users are created on any databases and is capable of setting permissions for other databases.

mongo --port 27017 --authenticationDatabase "vehicles" -u "barryvehicles" -p


Updating user details

We can change the information of the user with an updateUser() command. When updating the user’s roles must be specified for all roles we want to be assigned, since updateUser()will overwrite any rules that are already in place.

In this instance we’ll modify our “barryvehicles” user by adding the custom field, and then grant access to the admin database. “customData” is a section that allows us to create any custom key pair “customData” section lets the creation of any key pair that we want to create. This does not affect the roles of users; however, custom fields are as a more informative section that allows us to add more information about the user.


db.updateUser( <"username">{, ", customData :{   }, roles: [ {role: , db: } ] } )


db.updateUser( "barryvehicles",  )


Removing an account

Users can be deleted by using dropUser() command. dropUser() command. In the following example, we’ll remove users “barryvehicles”.






Logging in

There are two ways of verifying the logs of MongoDB. We are able to:

  • Make sure you check the mongod log file
  • Make use of getLog() command. obtainLog() command

receiveLog() returns the most recent events logged. This command reads most recent 1024 MongoDB log entries stored in RAM. In previous versions of MongoDB the logs were displayed as plain text. However, with MongoDB 4.4 the logs are formatted using Extended JSON v2.0.


db.adminCommand( { getLog:  } )

The three options for options to using the obtainLog() command. They are

  • * provides the list of values that are available for the getLog() function.
  • global provides all the most latest log entries.
  • startupWarnings generates log entries that could contain warnings or errors since the beginning in the process currently being run.


db.adminCommand(  ) db.adminCommand(  )


Commands for managing databases

This section we’ll discuss the most basic commands for managing databases. These commands can help you determine database’s stats, statistics for collections and size of the collection, among others.


Help is an important option for any administrator’s toolbox. Help will show you a list with help options in MongoDB.

Normal assistance:



Here, you will find the various help options that are available in MongoDB. If you’d like to learn all help commands required to work with databases, use the command.


Get database details

Stats() is a command that provides statistics of the database. statistics() command provides statistics on the database. The information is provided includes everything from objects and collections (documents) and the size of the database to the number of indexes.

The scaleFactor is the way in which data sizes are displayed. The default scaleFactor value is 1, which displays the data in bytes. For instance, we could alter the scaleFactor to 1024 and show the size in Kilobytes.



If you’d like to know the details about the server, utilize to use the db.serverStats() command.



To find a list of connection names, you can use the the getCollectionNames()command



Retrieving and sending collection details

Find statistics on collection

This state() function will give an extensive summary of our collection.



Get collection latency

Utilize the latencyStatus() command to determine the average latency of the write, read and read operations as well as the total number of write and read operations.



Get collection sizes

The following commands can be employed to calculate the dimensions of Collections by a variety of methods:

  • dataSize() shows the dimensions of the data within the collection.
  • storageSize()indicates the total amount of storage available to documents in the collection.
  • totalSize() indicates the total amount of data in the collection, including indexes and documents.
  • TotalIndexSize() provides the index dimension of the data collection.

db.vehicledetails.dataSize() db.vehicledetails.storageSize() db.vehicledetails.totalSize() db.vehicledetails.totalIndexSize()


Since”vehicledetails “vehicledetails” are a very small collection and is not a large amount, storageSize is small. capacity of storage is equivalent to the totalIndexSize since the data indexed is the same as the raw data contained in the collection. Hence, further compression is not feasible.

Renaming collections

You can change the name of collections that are already in existence using the renameCollection function. (This feature is not supported by the sharded collection.)

When changing the name of a collection, we must specify both the source namespace as well as the namespace of the destination correctly. In MongoDB namespace, it is the name that is unique to the database in which we identify the database objects.

In the following example we have renamed”vehicledetails” to “vehicledetails” collection of the database for vehicles. We have identified the namespaces as . to distinguish between collection of the past and the new.Copy

db.adminCommand(  )


Stopping the server

If we wish to end the MongoDB instance it is possible to use an inbuilt shutdownServer() command. shutdownServer() will clean all resources used by databases prior to terminating the MongoDB process.

The command has to be issued on the administrator database for it to be executed. This can be accomplished through this function: obtainSiblingDB function to show that the database is admin.


db.shutdownServer({ force: , timeoutSecs:  })

The option to force option triggers an operation to shut down and stops all ongoing operations to shut down this MongoDB server. It is possible to use the timeoutSec option is used to specify the number of seconds prior to the shutdown taking place. If the environment is authenticated users must be granted the ability to shutdown in order to run this command.

In the next example, we’ll trigger to shut down the MongoDB instance within 10 seconds. This function getSiblingDB function lets us direct the shutdown function to the administrator database.



This concludes the MongoDB command tutorial. The above mentioned commands are available to further explore by consulting MongoDB’s official MongoDB document.

Leave a Reply

Your email address will not be published. Required fields are marked *