You can access all your MongoDB deployments using the Atlas UI, Compass UI or the MongoDB shell. Shell is the fastest and most convenient way to interact with the database, especially for experienced database administrators and developers.
In this article, we will discuss some of the important shell operations in MongoDB.
What is MongoDB Shell?
MongoDB shell, also known as mongosh is a JavaScript and Node.js REPL environment to interact with MongoDB deployments. MongoDB shell has some AI powered advanced features like syntax highlighting, contextual help, friendly error messages and intelligent autocomplete. You can also save the scripts as snippets to be used later.
MongoDB shell is open-source and extensible, which means that you can extend and add new functionality as new services and products are added to your MongoDB platform.
Installation
You can download the shell installable from MongoDB download center. You just need to select the file corresponding to your operating system (Windows, Linux, MacOS). Once you install, you can connect to your database server using the connection string and start querying the data, perform administration tasks, run scripts and much more.
Undoubtedly, shell is the fastest way to work with MongoDB. You can think of the MongoDB shell as the command line interface (CLI) of the MongoDB server.
MongoDB Shell also acts as a JavaScript interpreter, so any code you write can be executed on the shell. The mongosh also interprets multiline code.
Shell editors
You can use the built-in editor or an external editor. This is very useful for multiline code, as the terminal window may become messy with a lot of commands. To use the built-in editor, type the.editor
command, and for the external editor, type edit along with the editor to be used, for example the vi editor.
Database
By default, mongosh connects to the test database or the current database. You can quickly check and change your database. To show all the available databases on the server, use the show dbs
command. Then set the new database using the use <db_name>
command.
Collections
The show command can also be used to display collections, profiles, users, roles and logs. For example, to view all the collections, use the show command as show collections
. You can use the show command for viewing users, roles, profiles as well.
Similar to the use database command, you can use the use <collection_name> to point to a particular collection. For example, use accounts
Custom options
You can customize the strings that are displayed on the terminal screen. By default, the mongosh displays the current database name, but you can also write simple code to add the
line number, hostname, server status and stats.
MongoDB shell Commands
You can always use the help to know about commands. db.help
will list all the database methods. If you want help specifically on collection methods, you can use db.collection.help()
. “Collection” here refers to the name of the collection. For example, db.accounts.help()
will show help methods on the accounts collection.
Let us move to the basic CRUD operations performed using the MongoDB shell:
Create operations
Create operations in MongoDB are of two types - insert a single document (insertOne) and insert multiple documents (insertMany()).
db.collection.insertOne(<field -value pairs="">)
</field>
Here, db refers to the current database. You need to replace “collection” with the actual collection name. Inside the brackets, you can add all the field-value pairs for the document.
For example,
db.employees.insertOne({name: "Joe", deptt: "HR", dob: "19/05/1982", doj: "03/06/2023"})
insertMany() is used to perform bulk insert operations, separated by flower braces. For example,
db.employees.insertMany(
{name: "Joe", deptt: "HR", dob: "19/05/1982", doj: "03/06/2023"},
{name: "Zack", deptt: "Admin", dob: "21/03/1979", doj: "01/06/2019"},
{name: "Mary", deptt: "Infrastructure", dob: "10/11/1993", doj: "05/06/2021"}
)
In the above examples, all the values are stored as strings, however MongoDB, due to the BSON type, allows date, int, float and many other data types as well.
Read operations
MongoDB supports read operations through many variations of the find() command. You can add multiple filters, aggregation pipeline stages, projections and much more to get only the data that is absolutely required. For example,
db.employees.find()
This will return all the documents of the employees collection.
To get the collection with the name “Zack”, you can add the filter as:
db.employees.find({name: "Zack"})
The above will return all the fields present in the document. If you want to get only specific fields, you can mark the fields you do not want to return as 0, or those you want as 1. The _id field is displayed by default, unless you explicitly mark it as 0.
db.employees.find({name: "Zack"}, {name: 1, doj: 1, _id:0})
Update operations
MongoDB provides flexible options to update existing data.
To update a single document, you can use db.collection.updateOne() and place the update condition inside the parentheses. For example,
db.employees.updateOne({name: "Zack"}, { $set: { deptt: "HR" } })
To update many documents, you can use the updateMany() command as follows:
db.users.updateMany({ deptt: "HR" },{ $set: { deptt: "Human Resources" } })
MongoDB also allows replacing entire documents instead of a single field. For this, you can use the method replaceOne(). In this case, the entire document is replaced by the new document provided with the command. The details of the old document will be lost.
db.employees.replaceOne({name: "Zack"}, {deptt: "HR"})
In the above example, for the user Zack, we will lose all the details except the deptt. This method is good, if you want to change multiple fields of a single document.
An update operation returns error, if the document is not found, hence cannot be updated. In some cases, we would like to insert the document, if it is not present. For this, MongoDB provides an option called upsert, that can be passed to the update method. Upsert is a boolean. If true, MongoDB will insert the document, if it does not exist.
db.employees.updateMany(
{ name: "Jos" },
{ $set: {deptt: "admin"} },
{ upsert: true}
)
Delete operations
Similar to insert and update, you can delete single or multiple entries in MongoDB. To delete one document, use deleteOne() and to delete multiple documents, use deleteMany() method.
db.employees.deleteOne({ deptt: "admin" })
Note that the above command will delete the first document it encounters with the matching criteria.
db.users.deleteMany({ deptt: "admin" })
Comparison operators
MongoDB provides a rich set of commands for complex queries. These commands are used along with the CRUD operations for filtering and sorting data to get the desired results. You can use these commands with the read, update and delete operations.
$eq - Use the operator to find an equal match. For example, to find all the employees with the deptt admin.
db.employees.find({ deptt: { $eq:"HR" } })
$ne - Exactly opposite to the $eq, $ne finds the value that is not equal to the specified value.
db.employees.find({ deptt: { $ne:"HR" } })
$gt - returns values that are greater than the specified value. Let’s say that we have another field named salary in our employee documents.
db.employees.updateMany(
{ salary: {$gt: 100000} },
{ $set: {status: "bonus_5pc"} },
{ upsert: true}
)
You can also use the $gte to include values that are equal to the specified value. For example, in the above command, the salary value of 100000 will not be included, however if we use $gte, this will also fetch the values equal to 100000 in the result.
We have $lt and $lte similar to the above to find values less than and less than equal to the specified value respectively.
db.employees.updateMany(
{ salary: {$lt: 100000} },
{ $set: {status: "bonus_15pc"} },
{ upsert: true}
)
$in - This operator finds any of the values specified in the array of values. For example, to find the employees of HR and admin deptt, we can specify the $in operator, instead of the $eq operator.
db.employees.find( { deptt: { $in: ["HR", "admin"] } )
$nin - $nin works exactly in an opposite manner to $in, by finding values that are not present in the specified set of array values.
db.employees.find( { deptt: { $nin: ["HR", "admin"] } )
The above command will return all the values where the deptt is not equal to HR or admin.
Miscellaneous commands
You can also perform complex updates to documents with the below operators in a single command/query:
$inc - Increase the value of the specified field with the specified value, for the documents that match a certain given criteria. For example,
db.employees.updateMany({ salary: {$lte:50000} }, {$inc: { salary: 5000} })
The above will increase the salaries of those having salaries less than or equal to 50000 by an amount of 5000.
$min - This operator compares the value of a given field with the specified value. If the given value is less than the field value, the field value is updated to the given value.
db.employees.updateMany({ $min: {salary:400000} })
The above command will update the salary field for all the documents that have a salary value more than 400000, to 400000.
$max - This operator updates the fields, only if the given value is greater than the existing field value. For example,
db.employees.updateMany({ $max: {salary:500000} })
The above command will change the salary field of those having a salary less than 500000, to 500000.
You can also rename a field using the $rename operator:
db.employees.updateOne( { $rename: {'salary': 'base_salary'} )
In the above command, the salary field is renamed to the base_salary field in the collection.
You can use a set of operators to get the results in the desired order and format.
.sort() - The sort() method is used with the find() command to get the results in a particular manner. For example, you can sort the results of the employees collection in alphabetical order, or date of joining, or the salary, from lower to higher or vice versa. You can use multiple sort parameters to group items. For example, after sorting by name, you can also sort by doj, and then salary all in a single command.
db.employees.find().sort({ name: 1, doj:1, salary: -1 })
1 specifies min to max order, while -1 represents reverse order.
.limit() - This method limits the number of results obtained. For example, you can restrict the results to the first 5 documents.
db.employees.find().limit(5)
.skip() - This method skips a certain specified number of documents before displaying the results.
db.employees.find().skip(5)
The command will skip the first 5 documents and display the rest.
Aggregation commands
MongoDB’s rich set of aggregation pipeline commands makes it unique and unparalleled to other databases, where a lot of transformation has to be done within the application. In MongoDB, you are able to get the desired results by providing all the filters in a single query itself using different stages of the MongoDB aggregation pipeline.
The basic method that provides access to all the aggregation methods is the aggregate() method. You can provide as many stages as you want inside this method, for example, $match, $group, $sort, $limit and so on.
A typical pipeline consists of a $match (1st stage), $group (2nd stage) and $sort (3rd stage) to get the results. The $match matches the documents that satisfy our condition (for example, salary less than 50000), the $group then groups the data for those documents received in the first stage (for example, group the employees having salary less than 50000 based on their date of joining) and then $sort the data (for example, display results in ascending order of salary).
$group - The $group stage performs all the aggregations and groupings based on the given condition. You can use the following operators:
$count - counts the number of documents in the specified group.
$max - returns the maximum value of the field that is used for grouping.
$min - returns the minimum value of the field that is used for grouping.
$avg - returns the average value of the field in the collection used for grouping
$sum - returns the sum of the field’s values in the collection.
$unwind - Another useful stage in the aggregation pipeline is the $unwind stage, which is used to loop through fields of arrays. Let us say you have an array of interns with the following data:
{
hospital_name: "Columbus Premium",
city: "New York",
location: {
type : 'Point',
coordinates : [ -5.6722512,17, 40.9607792 ]
},
interns: [
{ year : 2023, age : 21 },
{ year : 2022, age : 23},
{ year : 2021, age : 21 },
{ year : 2023, age : 22 }
]
}
You can apply the unwind operator to get each value in the array as a separate document:
db.interns.aggregate([
{ $match : { city : 'New York' } },
{ $unwind : '$interns' }
])
Indexing
You can also perform indexing from the MongoDB shell. Some important methods are:
createIndex() - creates an index on the specified field. Example:
db.employees.createIndex("salary")
dropIndex() - drops the given index from the database
db.employees.dropIndex("salary")
If you want to delete all the indexes of a particular collection, you can use the method
db.employees.dropIndexes()
The above will remove all the indexes except the _id index.
To remove multiple indexes, you can use dropIndexes and give the name of the indexes inside the parentheses, separated by commas.
db.employees.dropIndexes("salary", "name")
To get a list of existing indexes, MongoDB provides the method getIndexes()
Summary
In this article, we have discussed the most commonly used MongoDB shell commands by the developers. MongoDB provides many other commands, used by admins and developers to monitor databases and perform advanced admin operations, like sharding, managing roles and access, and replication. We will be discussing those in the upcoming articles.