This guide provides an in-depth overview of commonly used MongoDB shell commands, categorized by their functions, with examples and summaries to ensure clarity.
Table of Contents
MongoDB Shell (mongosh) is an interactive JavaScript interface used to interact with MongoDB instances. It allows users to perform various operations like querying, updating data, and managing databases directly from the command line.
Prerequisites
Before diving into the MongoDB shell commands, ensure you have:
- MongoDB Installed: Download and install MongoDB from the official MongoDB website.
- MongoDB Shell (mongosh): Use the MongoDB Shell (mongosh), which is included in MongoDB installations starting from version 5.0.
To connect to your MongoDB instance, open a terminal and type:
mongosh
If you’re connecting to a specific MongoDB instance or cluster, use:
mongosh "mongodb+srv://<cluster-url>"
Replace with the connection string for your MongoDB deployment.
List of MongoDB Shell Commands
The MongoDB shell is an interactive JavaScript interface to MongoDB, which allows users to insert new objects into the database, query the existing collections, and perform administrative tasks for managing the database, its data, and its users.
See below for list MongoDB Shell commands:
1. Database Operations
These Mongodb shell commands help you manage and switch databases.
a. List Databases
show dbs
Lists all databases along with their sizes. Example:
admin 0.000GB config 0.001GB local 0.000GB
Use this command to view available databases on your server.
The operation corresponds to the listDatabases command. If the deployment runs with access control, the operation returns different values based on user privileges. See listDatabases Behavior for details.
b. Switch Database
To switch databases, issue the use <db> helper, as in the following example:
use <database_name>
Switches to the specified database. If it doesn’t exist, it will be created once data is added.
c. Drop Database
Deletes the currently selected database.
db.dropDatabase()
Example:
use testDatabase db.dropDatabase()
Removes a database and all its collections permanently.
d. View Database Statistics
Displays statistics about the current database, such as the number of collections, storage size, and indexes. Example output:
{ "db": "test", "collections": 5, "views": 0, "objects": 250, "avgObjSize": 120, "dataSize": 30000, "indexes": 5, "indexSize": 4096 }
Provides an overview of the database’s structure and storage.
2. Collection Operations
Collections in MongoDB are analogous to tables in relational databases.
a. List Collections
Displays all collections in the current database.
Useful for verifying the collections available in the active database.
b. Create Collection
db.createCollection("collection_name")
Creates a new collection.
Example:
db.createCollection("inventory")
While MongoDB creates collections automatically when data is inserted, this command allows manual creation with options for validation rules.
c. Drop Collection
Removes the specified collection.
Example
db.inventory.drop()
Removes the collection permanently. Use it cautiously to avoid data loss.
3. CRUD Operations
a. Insert Documents
Insert single or multiple documents into a collection.
- Single Document:
- Multiple Documents:
b. Read Documents
Retrieve documents from a collection.
- Find All:
- Find with Query:
- Formatted Output:
c. Update Documents
Modify existing documents.
- Update One:
- Update Many:
d. Delete Documents
Remove documents from a collection.
- Delete One:
- Delete Many:
4. Indexing
Indexes improve query performance.
a. Create Index
Indexes improve query performance by organizing documents efficiently. Use 1
for ascending or -1
for descending.
Creates an ascending index on the specified field.
b. View Indexes
c. Drop Index
Removes a specific index from a collection.
5. Aggregation
Aggregation frameworks allow you to process and analyze data.
a. Basic Aggregation Pipeline
6. Administrative Mongodb Shell Commands
a. View Current Operations
Shows currently running operations.
b. Kill a Process
Terminates the specified operation.
c. Server Status
Provides comprehensive details about the database server, such as uptime, memory usage, and connections.
d. Storage Statistics
Provides a detailed report about a collection, including document count, storage size, and index usage. This helps optimize performance and storage.
Displays storage statistics for a specific collection, including document count, index sizes, and allocated storage.
7. User Management
a. Create User
b. Remove User
8. Backup and Restore
a. Export Data
b. Import Data
Credits
- Photo by Athul Cyriac Ajay on Unsplash
Reference:
Conclusion
MongoDB Shell commands provide powerful tools for database management, ranging from basic CRUD operations to advanced administrative tasks. By mastering these Mongodb shell commands, you can efficiently interact with and manage MongoDB databases.
Let us know if you’d like deeper insights into any specific MongoDB shell commands or advanced use cases!