The basic commands of MongoDB include connecting to the database, listing existing databases, and collections, creating databases and collections, inserting documents, updating documents, deleting documents, etc. MongoDB provides a powerful set of commands that allow us to interact with the database, view collections, monitor MongoDB, and perform administrative tasks from CLI or GUI.
Here, we provided some basic common commands used in MongoDB. Note that all these basic commands are executed with MongoDB 6.0 version.
Table of contents
1. Basic MongoDB Commands
The legacy Mongo shell command mongo
was deprecated in MongoDB 5.0 and removed in MongoDB 6.0. The new Mongo shell command mongosh has improved and has many advantages, for example, compatibility with the MongoDB Node.js driver, better syntax highlighting, improved error messages, and enhanced auto-completion.
1.1 Connect to MongoDB
Run the mongosh
command to connect to the MongoDB. This command by default connects to ‘test
‘ database.
# Use mongosh command
mongosh
mongosh –nodb command
You can also launch MongoDB Shell without first connecting to a particular database with the mongosh --nodb
command. As a result, we can perform administrative commands, connect to databases, and complete other operations using the shell without a special database environment.
# Usage of --nodb command
mongosh --nodb
Hence, we are in the mongosh shell with no database connection.
Note that if you used mongosh --nodb
, exit from command and use just mongosh
to continue the below article and run these basic commands.
1.2 show.help command
In MongoDB, basic information on databases, collections, indexes, and other system components can be viewed using the show
command. To see a list of available sub-commands for the show command, we can use the help option like this.
# Usage of show.help command
show.help
Therefore, it displayed a list of the subcommands that are accessible to use with the show command.
Let’s look at some show commands in the below sections.
1.3 Show Databases Command
The show dbs command can be used to list the database currently present in MongoDB of our system. We can use the show command with the databases
keyword or either dbs
. Both generate the same results.
# Usage of show dbs command
show dbs
This, the above command generates a list of available databases below.
1.4 Create or Change Database
As you learned by default the mongosh command connects to the test database. However, you can change this and connect to any of your databases by using the use
command.
Note that If the database name used with the use
command doesn’t exist, this creates a new empty database.
# Syntax of use command
use [db name]
# use command to switch database
use MyDatabase
# Output:
# switched to db MyDatabase
1.5 Create Collection
The createCollection()
method is used to create the collection in the current database. The takes the collection name you wanted to create as an argument.
# Syntax of creating collection
db.createCollection("[collection name]")
# Examples
db.createCollection("course")
db.createCollection("student")
db.createCollection("users")
The above example creates three collections course
, student
and users
. To verify that the collection has been created, you can list all the collections in the current database using the show collections
command.
1.6 Show Collections Command
The list of collections from the current database can be viewed via the show command of MongoDB. All you have to do is place the keyword collections
along with the show command.
# Usage of show collections command
show collections
The collections stored in the database are listed as follows.
1.7 Insert Documents into the Collection
To insert documents into a MongoDB collection, you can use the insertOne()
method to insert a single document or the insertMany()
method to insert multiple documents at once. Here are examples of how to insert documents using both methods in a Node.js environment with the official MongoDB Node.js driver:
# Syntax
db.[collection name].insert({})
# Example of insert one document
db.student.insert({"name": "Chris", "gender": "M"})
# Example of insert multiple documents
db.student.insert([
{"name": "Lyn", "gender": "F"},
{"name": "Scott", "gender": "M"},
{"name", "Dan", "gender": "M"}
])
1.8 List Documents from the Collection
Use the find()
method to list or query documents from a MongoDB collection. This method retrieves documents from a collection based on specified criteria. Here’s how you can list documents from a MongoDB collection student
using the find()
method. Additionally, you can use the .pretty()
to print the documents well indented list.
# Syntax to list documents
db.[collection name].find()
#or
db.[collection name].find().pretty()
# Example
db.student.find()
1.9 Update Document
The update() method is used to update the document in a collection.
# Syntax
db.[collection name].update({},{$set: {}})
# Example of updating document
db.student.update(
{"name":"Dan"},
{$set:
{"name": "NNK"}
}
)
1.10 Remove Collection from Document
To remove the collection from the document use the remove() method.
# Syntax
db.[collection name].remove({})
# Example
db.student.remove({"name":"NNK"})
2. Basic MongoDB Admin Commands
2.1 “setFreeMonitoring” command
Next, we have the setFreeMonitoring
command of MongoDB which is available in MongoDB version 4.0 and later, and it is used to set up a free tier monitoring service. The setFreeMonitoring
command called with the action parameter is used to enable or disable free cloud-based monitoring for a MongoDB deployment. Here’s a command of setFreeMonitoring
with the enable
action.
# Usage of setFreeMonitoring command
db.adminCommand(
{
setFreeMonitoring: 1,
action: "enable"
}
)
Similarly, we used the disable action to disable the free monitoring service like this.
# Usage of disable option
db.adminCommand(
{
setFreeMonitoring: 1,
action: "disable"
}
)
2.2 “CreateUser” command
Further, if we are required to create a new user with a specified set of privileges, then, we should use the CreateUser
command of MongoDB is given as follows.
# Usage of CreateUser command
db.adminCommand(
{
createUser: "User21",
pwd: passwordPrompt(),
roles: [
{ role: "dbOwner", db: "admin" }
]
}
)
Above, we create a new user named User21
with the password entered by the user at runtime. The new user is granted the dbOwner
role on the admin
database, which provides full access to the database.
Hence, the output verifies that the user is created under the specified privileges.
2.3 “hostInfo” command
There, we have the hostInfo
command which is the MongoDB administrative command. It retrieves information about the host where the MongoDB instance is running. Here is the command given with its parameters.
# Usage of hostInfo command
db.adminCommand(
{
hostInfo: 1
}
)
The output displayed various details about the host, including its operating system, architecture, and CPU information.
3. “explain” command
There, we have another command which is explain
to provide information about a query execution by the database. The explain command here is used with the find command.
# Usage of explain command
db.student.find().explain()
Here, the explain()
command is used to get an object that provides information about the query plan used by MongoDB to execute the find()
method on the student collection.
The following output contains the details about the query.
More details about explain command can be found here.
4. MongoDB “getLogComponents” command
In addition to all the above commands, we have the getLogComponents
command in MongoDB to retrieve information about the current logging verbosity and levels for various components of the MongoDB system.
# Usage of getLogComponents command
db.getLogComponents()
Here, it includes the following logging information for all components of the MongoDB system.
More details about other MongoDB commands can be found here.
2. Conclusion
In conclusion, we have discussed some common basic commands of MongoDB. Among the many commands that MongoDB supports, these are just a few. However, the MongoDB documentation has an extensive set of commands.
Related Articles
- Using MongoDB Index Explained
- MongoDB Create User
- List Databases in MongoDB
- MongoDB Interview Questions
- Check MongoDB Version
- Node.js Using Express.js with MongoDB
- MongoDB Create Database & Collection
- MongoDB updateOne() method Explained
- Using Mongoose Module with MongoDB
- MongoDB Client Tools (Interact with MongoDB)
- Using MongoDB Index Explained
- MongoDB Schema
- MongoDB vs MySQL Differences