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.
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.
Visit the official page, pick the Windows version, and start downloading.
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
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
Upon the successful installation, authenticate the installed version:
mongod --version
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
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
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.
Once connected, you can work with their DBs. Before it, the interface greets a message:
The assigned DB on a freshly launched shell instance is called a test. It is safe to use for experimenting.
Useful operations are given below:
First, run show dbs
, which gives a view of every database that is available:
show dbs
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
Enter the use command with the DB name, e.g., new_db
, to create or switch to the specified one:
use new_db
Replace new_db
with the actual name of the DB.
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'})
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'}
])
Once the input is inserted, display the existing collections:
show collections
If you have not done any task, leave the interface by executing:
exit
You have to understand the basic shell operations.
When working with the shell, CRUD (Create, Read, Update, Delete) operations are essential. Let’s perform some basic ones:
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" })
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
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 } })
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" })
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.
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 } }
])
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.
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
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:
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 })
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 })
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)
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)
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
By mastering the MongoDB command, you gain valuable insights into data.
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 MongoDB cloud database in a few seconds and start working in no time.