Basic Mongo Shell Commands Complete Guide
Understanding the Core Concepts of Basic Mongo Shell Commands
Basic Mongo Shell Commands
1. Connecting to MongoDB
Before you can run any commands, you need to connect to your MongoDB instance. If your MongoDB server is running locally and on the default port (27017), you can connect using:
mongosh
If your MongoDB server is running on a different host or port, or if you need to provide authentication details, you can specify these when connecting:
mongosh "mongodb://<username>:<password>@<host>:<port>/<database>"
Example:
mongosh "mongodb://user:password@localhost:27017/mydatabase"
2. Managing Databases
a. Displaying Databases:
To see a list of all databases, use the command:
show dbs
b. Switching to a Database:
You can switch to a different database using the use
command:
use <database_name>
Example:
use mydatabase
If the database does not exist, MongoDB will create it once you start inserting data.
c. Dropping a Database:
To delete a database, use the dropDatabase()
command while you are in the context of the database you want to delete:
db.dropDatabase()
3. Managing Collections
a. Displaying Collections:
To list all collections in the current database, use:
show collections
b. Creating a Collection:
You can create a new collection explicitly using createCollection()
, or implicitly by inserting documents into a new collection:
Explicit:
db.createCollection("<collection_name>")
Implicit:
Insert a document and MongoDB will automatically create the collection if it doesn’t exist:
db.<collection_name>.insertOne({ <field1>: <value1>, <field2>: <value2> })
c. Dropping a Collection:
To delete a collection, use:
db.<collection_name>.drop()
4. CRUD Operations
a. Create - Inserting Documents:
To add a single document, use insertOne()
:
db.<collection_name>.insertOne({ <field1>: <value1>, <field2>: <value2> })
To insert multiple documents, use insertMany()
:
db.<collection_name>.insertMany([{ <field1>: <value1> }, { <field2>: <value2> }])
b. Read - Querying Documents:
To find all documents in a collection:
db.<collection_name>.find()
To format the output in a readable way use pretty()
:
db.<collection_name>.find().pretty()
To find documents that meet certain criteria, pass a query object:
db.<collection_name>.find({ <field>: <value> })
c. Update - Modifying Documents:
To update a single document, use updateOne()
:
db.<collection_name>.updateOne({ <field>: <value> }, { $set: { <field>: <new_value> } })
To update multiple documents that match a criteria, use updateMany()
:
db.<collection_name>.updateMany({ <field>: <value> }, { $set: { <field>: <new_value> } })
d. Delete - Removing Documents:
To delete a single document, use deleteOne()
:
db.<collection_name>.deleteOne({ <field>: <value> })
To delete multiple documents that match a criteria, use deleteMany()
:
db.<collection_name>.deleteMany({ <field>: <value> })
5. Indexing
Indexes can significantly speed up your queries. Here’s how to create a basic index:
db.<collection_name>.createIndex({ <field>: <1/-1> })
- Use
1
for ascending order. - Use
-1
for descending order.
Example:
db.users.createIndex({ username: 1 })
6. Aggregation
The MongoDB Aggregation Framework allows for complex data processing pipelines.
Example: To find the average age:
db.users.aggregate([
{ $group: { _id: null, averageAge: { $avg: "$age" } } }
])
7. Administration and Monitoring
a. Show Server Status:
To get detailed information about the current MongoDB server, use:
db.serverStatus()
b. Show Replication Status:
To view the status of a replica set, use:
rs.status()
c. Show Log Files:
To examine MongoDB log files:
db.getLogComponents()
db.setLogLevel(1, "global")
db.getLogLevel()
d. Show Users:
To list all users and their roles:
Online Code run
Step-by-Step Guide: How to Implement Basic Mongo Shell Commands
Before We Begin
- Install MongoDB: Ensure that you have MongoDB installed on your system.
- Run the Mongo Shell: Open a terminal or command prompt and type
mongo
to start the shell.
Step 1: Connect to MongoDB
When you type mongo
, the shell connects to the local instance of MongoDB (running on port 27017).
> mongo
MongoDB shell version v5.0.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7b49d5e6-1234-5678-9abc-f6a4e8c9f12d") }
MongoDB server version: 5.0.8
Atlas atlas-abcdef-shard-0 [primary] test>
Here, test
is the current database we are connected to in the shell.
Step 2: Switch Database (use)
Use the use
command to switch to an existing database or create a new one if it doesn't exist.
# Switch to a new database named 'myDatabase'
> use myDatabase
switched to db myDatabase
Note: Databases are not created until you store data in them.
Step 3: List Databases (show dbs)
Display all databases on the server.
# List all databases
> show dbs
admin 0.000GB
config 0.001GB
local 0.000GB
Initially, you will see only the default databases (admin
, config
, local
). As soon as you insert data into myDatabase
, it will appear in the list.
Step 4: Create/List Collections (db.createCollection() / show collections)
Collections are similar to tables in other databases. You can list all collections in the current database or create a new collection.
# Create a new collection named 'employees'
> db.createCollection('employees')
{ "ok" : 1 }
# List all collections in current database
> show collections
employees
Alternatively, if you insert documents directly into a collection without explicitly creating it, MongoDB will create it automatically:
# Insert document into a new collection
> db.employees.insertOne({ "name": "John", "position": "Developer", "salary": 75000 })
# List collections again
> show collections
employees
Step 5: Insert Documents (db.collection.insertOne(), db.collection.insertMany())
Documents are stored in collections and represent individual records inside these collections. You can insert one document or multiple documents at a time.
Insert One Document:
# Insert a single document into the 'employees' collection
> db.employees.insertOne({ "name": "Jane", "position": "Designer", "salary": 60000 })
{
"acknowledged" : true,
"insertedId" : ObjectId("619c3c29b123456789abcd12")
}
Insert Multiple Documents:
# Insert multiple documents at once
> db.employees.insertMany([
{ "name": "Mike", "position": "Manager", "salary": 80000 },
{ "name": "Liz", "position": "QA", "salary": 55000 }
])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("619c3cde123456789abcd134"),
ObjectId("619c3cde123456789abcd156")
]
}
Step 6: Query Documents (db.collection.find())
To retrieve documents from a collection, use the find()
method.
Retrieve All Documents:
# Retrieve all documents from 'employees' collection
> db.employees.find().pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 60000
}
{
"_id" : ObjectId("619c3cde123456789abcd134"),
"name" : "Mike",
"position" : "Manager",
"salary" : 80000
}
{
"_id" : ObjectId("619c3cde123456789abcd156"),
"name" : "Liz",
"position" : "QA",
"salary" : 55000
}
The pretty()
function formats the output to be more readable.
Retrieve Specific Documents:
# Find all employees who are Designers
> db.employees.find({ position: "Designer" }).pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 60000
}
Step 7: Update Documents (db.collection.updateOne(), db.collection.updateMany())
Modify documents inside a collection using these methods.
Update One Document:
# Change Jane's salary to 62000
> db.employees.updateOne({ name: "Jane" }, { $set: { salary: 62000 } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
# Check updated document
> db.employees.find({ name: "Jane" }).pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 62000
}
Update Many Documents:
# Give a raise to all employees in the QA position
> db.employees.updateMany({ position: "QA" }, { $inc: { salary: 3000 } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
# Check all updated documents
> db.employees.find().pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 62000
}
{
"_id" : ObjectId("619c3cde123456789abcd134"),
"name" : "Mike",
"position" : "Manager",
"salary" : 80000
}
{
"_id" : ObjectId("619c3cde123456789abcd156"),
"name" : "Liz",
"position" : "QA",
"salary" : 58000
}
Step 8: Delete Documents (db.collection.deleteOne(), db.collection.deleteMany())
Remove documents from a collection as needed.
Delete One Document:
# Remove John from the 'employees' collection
> db.employees.deleteOne({ name: "John" })
{ "acknowledged" : true, "deletedCount" : 1 }
# Verify John is gone
> db.employees.find().pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 62000
}
{
"_id" : ObjectId("619c3cde123456789abcd134"),
"name" : "Mike",
"position" : "Manager",
"salary" : 80000
}
{
"_id" : ObjectId("619c3cde123456789abcd156"),
"name" : "Liz",
"position" : "QA",
"salary" : 58000
}
Delete Many Documents:
# Fire all employees in QA department
> db.employees.deleteMany({ position: "QA" })
{ "acknowledged" : true, "deletedCount" : 1 }
# Verify no QA employees remain
> db.employees.find().pretty()
{
"_id" : ObjectId("619c3c29b123456789abcd12"),
"name" : "Jane",
"position" : "Designer",
"salary" : 62000
}
{
"_id" : ObjectId("619c3cde123456789abcd134"),
"name" : "Mike",
"position" : "Manager",
"salary" : 80000
}
Step 9: Drop a Collection or Database
If you need to remove a collection or an entire database:
# Drop the current employees collection
> db.dropCollection('employees')
true
# Switch to admin database
> use admin
# Drop the 'myDatabase' database
> db.dropDatabase()
{ "dropped" : "myDatabase", "ok" : 1 }
# Check the list of existing databases - the 'myDatabase' should be gone
> show dbs
admin 0.000GB
config 0.001GB
local 0.000GB
Step 10: Basic Aggregation Pipeline (db.collection.aggregate())
Aggregation pipelines allow you to perform complex data transformations.
# Calculate average salary of all employees in a department using the aggregation pipeline
> db.employees.insertMany([
{ "name": "John", "position": "Developer", "salary": 75000 },
{ "name": "Sam", "position": "Developer", "salary": 76000 },
{ "name": "Sarah", "position": "Manager", "salary": 81000 }
])
# Aggregate data
> db.employees.aggregate([
{ $group: { _id: "$position", AverageSalary: { $avg: "$salary" }} }
]).pretty()
{
"_id" : "Manager",
"AverageSalary" : 81000
}
{
"_id" : "Developer",
"AverageSalary" : 75500
}
This query groups the documents by the position
field and calculates the average salary for each group.
Summary
- Connect to MongoDB:
mongo
- Switch Database:
use <database_name>
- List Databases:
show dbs
- Create/List Collections:
db.createCollection('<collection_name>')
,show collections
- Insert Documents:
db.<collection_name>.insertOne({...})
,db.<collection_name>.insertMany([...])
- Query Documents:
db.<collection_name>.find({...}).pretty()
- Update Documents:
db.<collection_name>.updateOne({...},{...})
,db.<collection_name>.updateMany({...},{...})
- Delete Documents:
db.<collection_name>.deleteOne({...})
,db.<collection_name>.deleteMany({...})
- Drop a Collection or Database:
db.dropCollection('<collection_name>')
,db.dropDatabase()
- Aggregate Data:
db.<collection_name>.aggregate([...]).pretty()
Top 10 Interview Questions & Answers on Basic Mongo Shell Commands
1. What is the MongoDB Shell?
Answer: The MongoDB Shell, also known as mongosh
, is an interactive command-line interface for MongoDB. It allows you to execute JavaScript-based queries and instructions directly against a MongoDB database. The shell provides a way to manage databases, collections, documents, and perform operational tasks.
2. How do I connect to a MongoDB instance using the shell?
Answer: To connect to a local MongoDB instance (running on the default port 27017), simply open your terminal or command prompt and type:
mongosh
For connecting to a remote MongoDB server, use the following command format:
mongosh "mongodb://<hostname>:<port>/<database>"
For example:
mongosh "mongodb://192.168.1.10:27017/mydatabase"
3. How can I list all the databases on my MongoDB server?
Answer: To display all the databases available on your MongoDB server, use the show dbs
command in the shell:
show dbs
This will return a list of all databases along with their sizes.
4. How do I switch between databases in the MongoDB shell?
Answer: To switch to a different database within the MongoDB shell, use the use <database>
command:
use mydatabase
If the database does not exist, MongoDB will create it when you first store data into that database.
5. How can I list all collections of a current database?
Answer: To show all collections within the currently selected database, use the show collections
command:
show collections
This command returns a list of all collections in the active database.
6. How do I insert a new document into a collection?
Answer: You can insert a single or multiple documents into a collection using the insertOne()
method for one document or insertMany()
for several documents. Here’s how:
Single Document:
db.mycollection.insertOne({name: "Alice", age: 25, city: "Los Angeles"})
Multiple Documents:
db.mycollection.insertMany([{name: "Bob", age: 30, city: "Chicago"},
{name: "Carol", age: 22, city: "New York"}])
7. How can I retrieve all documents from a collection?
Answer: To query all documents in a specific collection, use the find()
method without any criteria:
db.mycollection.find()
To get the output in a more readable format, append .pretty()
:
db.mycollection.find().pretty()
8. How do I find specific documents based on certain conditions?
Answer: Use the find()
method with a query object to filter documents. For example, to find all users who are from New York:
db.users.find({city: "New York"}).pretty()
Or, to find users whose age is greater than 25:
db.users.find({age: {$gt: 25}}).pretty()
This uses a MongoDB query operator, $gt
for “greater than.”
9. How can I update documents in a collection?
Answer: Use the updateOne()
or updateMany()
methods to modify existing documents based on a condition. Here are examples for both:
Update One Document:
db.users.updateOne({name: "Alice"},
{$set: {age: 26}})
This updates Alice's age to 26. Update Multiple Documents:
db.users.updateMany({city: "New York"},
{$set: {country: "USA"}})
This sets the country field to "USA" for all users residing in New York.
10. How can I delete documents from a collection?
Answer: Use deleteOne()
to remove the first document that matches the given condition, or deleteMany()
to remove all documents matching the condition. Examples include:
Delete Single Document:
db.mycollection.deleteOne({name: "Alice"})
Removes the first document where the name is Alice. Delete Multiple Documents:
db.mycollection.deleteMany({city: "Los Angeles"})
Deletes all documents having "Los Angeles" as the city.
Login to post a comment.