Learning Center
MongoDB

How To Use the MongoDB Shell

19 Dec 2024
Minhal Abbas
Minhal Abbas

MongoDB Shell is an adaptive JavaScript and Node.js REPL (Read-Eval-Print Loop) environment for dealing with MongoDB deployments. It is an important utility for querying data, administering databases, and running various operations. It provides an attractive view for controlling databases, whether you're using them on a remote server or MongoDB locally.

This article will demonstrate the step-by-step guidelines for utilizing the MongoDB shell.

Step 1: Installation of MongoDB Shell
Copy link

Before starting operations, confirm that users have installed it on the system. If not, first, download the appropriate version via the official site and consider the installation instructions for the system.

Windows
Copy link

Visit the official page, pick the Windows version, and start downloading.

macOS
Copy link

On the official page, choose the macOS version and begin the downloading process. Alternatively, use Homebrew by executing the commands:

brew tap mongodb/brew
brew install mongosh

Linux
Copy link

Consider the guidelines provided on the website for the Linux OS. For example, on a Debian-based operating system, follow these steps:

Add the GPG key for the MongoDB repository:

curl -fsSL https://pgp.mongodb.com/server-7.0.asc |  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

Add the MongoDB repository to your system:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

Update the package list:

sudo apt update

Install MongoDB:

sudo apt install mongodb-org -y

Image4

Upon the successful installation, authenticate the installed version:

mongod --version

Image6

Once the installation is done, enable, start, and check the services of it:

sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl status mongod

Image5

And if you’re looking for a reliable, high-performance, and budget-friendly solution for your workflows, Hostman has you covered with Linux VPS Hosting options, including Debian VPS, Ubuntu VPS, and VPS CentOS.

Step 2: Establish a Connection to an Instance
Copy link

Once the installation is done, you can establish connections to its instance. If it is local, enter mongosh. It establishes the connection to the instance by default. It is running at port 27017 on localhost:

mongosh

Image7

The following syntax is utilized to establish a connection to the remote server:

mongodb+srv://<username>:<password>@<cluster-url>/<db>?retryWrites=true&w=majority

Modify <username>, <password>, <cluster-url>, and <db> with original credentials and connection details.

Step 3: Navigation to the Terminal
Copy link

Once connected, you can work with their DBs. Before it, the interface greets a message:

Image7

Useful operations are given below:

Exploring all Databases
Copy link

First, run show dbs, which gives a view of every database that is available:

show dbs

Image10

Accessing the Current Database
Copy link

The majority of commands operate on a database or a collection that is contained within the database. In order to accomplish this, the object db represents the presently selected database and is available:

db

Image9

Switching to the Database
Copy link

Enter the use command with the DB name, e.g., new_db, to create or switch to the specified one:

use new_db

Image11

Replace new_db with the actual name of the DB.

Insertion of an Object
Copy link

First, enter a name as an object into the student_data in the existing new_db:

db.student_data.insertOne({name: 'School has 500 students'})

Image1

Users can also insert multiple documents into the student_data, each containing a name field with specified values. This allows for batch insertion of data into the collection:

db.student_data.insertMany([
{name: 'School has 500 students'},
{name: 'School has 600 students'}
])

Image8

Viewing Collections
Copy link

Once the input is inserted, display the existing collections:

show collections

Image14

If you have not done any task, leave the interface by executing:

exit

Image12

You have to understand the basic shell operations.

Step 4: Operations Using CRUD
Copy link

When working with the shell, CRUD (Create, Read, Update, Delete) operations are essential. Let’s perform some basic ones:

Creating/Inserting Data
Copy link

When inserting new information into the collection, employ the insertOne function. Let us create a new one and fill it with the required information, including name, age, and city

db.collection.insertOne({ name: "Harry", age: 45, city: "Sydney" })

Image13

Finding/Reading Data
Copy link

You can query documents that are associated with the collection by employing the find function. For instance, all entries with an age greater than 25 are retrieved:

db.collection.find({ age: { $gt: 25 } }) //  Condition where age is greater than 25

Image15

Modifying Data
Copy link

Use the updateOne or updateMany functions to make changes to documents that exist. For instance, the age with Harry's name is updated to 50 on the existing one:

db.collection.updateOne({ name: "Harry" }, { $set: { age: 50 } })

Image16

Deleting Data
Copy link

Use the deleteOne or deleteMany methods to eliminate entries from the collection that are available. This command removes one document from the available ones with the value John in the name field:

db.collection.deleteOne({ name: "John" })

Image17

Step 5: Advanced Usage
Copy link

In this step, carry out complex operations via the advanced functionalities. By offering debugging, profiling, and performance optimization tools, the shell helps you find bottlenecks and optimize your setup.

Aggregation Pipeline
Copy link

With the help of pipelines, readers can compute records and get calculated results. By using pipelines, create complex analytics and transformations that will assist you in extracting insightful information from your raw. For executing a pipeline of stages, utilize the aggregate function. Here’s a basic code example:

db.collection.aggregate([
    { $match: { status: "A" } },
    { $group: { _id: "$city", total: { $sum: "$amount" } } },
    { $sort: { total: -1 } }
])

Image18

In the script, the pipeline filters documents with status A, groups them by city, sums the amounts, and sorts the results in descending order.

One strong tool for data analysis and transformation is the aggregation pipeline. It is composed of several stages, each of which changes the stream of documents. These stages include:

$project: Selects or excludes specific fields.

$match: Applying a query condition to filter them.

$group: Merges input by a field and calculates aggregations.

$sort: Arrange entries according to a given field.

$limit: Restricts the amount of records.

$skip: Skips a specified number of records.

MapReduce
Copy link

An effective paradigm for computing huge datasets. For executing MapReduce jobs, utilize the mapReduce command:

// Sample collection data
db.collection.insertMany([
    { name: "Harry", age: 25, salary: 5000 },
    { name: "Buttler", age: 30, salary: 6000 },
    { name: "Morgan", age: 35, salary: 7000 }
]);

// Map function
var mapFunction = function() {
    emit(this.age, this.salary);
};

// Reduce function
var reduceFunction = function(keyAge, valuesSalaries) {
    return Array.sum(valuesSalaries);
};

// Run MapReduce
db.runCommand({
    mapreduce: "collection",
    map: mapFunction,
    reduce: reduceFunction,
    out: "results"
});

db.results.find().forEach(printjson); // Output the results

Image3

  • In this example, the mapFunction emits the age as the key and the salary as the value. 

  • The reduceFunction sums the salaries for each age group. 

  • The results are stored in a new collection called results, and the final output is printed using db.results.find().forEach(printjson).

The output is given below:

Image22

Projection
Copy link

Utilize the projection operator to specify which fields should be included or excluded from the result set. It retrieves all info associated with the particular query, e.g., displaying only the name and age fields. This offers anyone the ability to visualize specific results while excluding others. Let’s project only name and age fields:

db.collection.find({}, { name: 1, age: 1 }) 

Image19

Sorting
Copy link

Sort the results employing the sort function. It retrieves every document belonging to the set. Then, sort them in descending sequence based on the age. It gives a view with the highest age values first. Let’s sort by age in descending order:

db.collection.find().sort({ age: -1 }) 

Image20

Limiting
Copy link

Users limit the entries of results via the limit function. For instance, obtain the initial three documents linked to the collection. It is useful for previewing a small subset of information without fetching the entire list. Let’s limit to 3 results:

db.collection.find().limit(3) 

Image21

Skipping
Copy link

Skip an entry is done via the skip function. For instance, skipping the initial two documents that linked to the collection. It is beneficial for paginating results or ignoring an entry of initial documents. Let’s skip the first 2 results:

db.collection.find().skip(2) 

Image23

Step 6: Scripting with Shell
Copy link

Scripts for task automation can be written by users within the shell. To achieve it, save the script in the .js file and run the mongosh. It is beneficial for executing repetitive tasks efficiently, e.g., data seeding or batch updates:

mongosh script.js

Image2

By mastering the MongoDB command, you gain valuable insights into data.

Conclusion
Copy link

With the help of the immersive MongoDB shell interface, you conduct repetitive management tasks like writing, reading, and manipulating. In addition, query existing collections, add new objects to the DB, and carry out management administrative tasks. From simple CRUD tasks to complex aggregations and scripting, users can efficiently utilize the interface to carry out a variety of activities. 

By executing scripts, readers efficiently perform repetitive tasks. This tutorial has covered the installation, configuration, and managerial tasks for managing the DBs, their collections, and their users. 

At Hostman, you can deploy a cloud database in a few seconds and start working in no time.