How to use MongoDB Shell

0 Shares
0
0
0
0

Introduction

Database systems like MongoDB are typically used with an external application that connects to the database server and performs operations such as reading and processing data or writing new entries. In cases like this, you are not interacting directly with the database server. Direct access may be required to perform administrative tasks on the database or to run ad hoc database queries.

This is where the MongoDB shell comes in. The MongoDB shell is an interactive console that you can use to connect to the database server and run commands on it, allowing you to perform administrative tasks and read, write, or manipulate data directly. The MongoDB shell enables you to connect to the database via the command line and work with it interactively from a terminal window. It also allows you to run external scripts to perform repetitive tasks with greater ease.

In this tutorial, you will use the MongoDB shell to connect to a MongoDB database and query the database interactively. You will also use the built-in help system and autocomplete features available in the shell.

Prerequisites
  • A server with a regular, non-root user with sudo privileges and a firewall configured with UFW. This tutorial has been verified using a server running Ubuntu 20.04.
  • MongoDB installed on your server.
  • Your MongoDB server instance is secured by enabling authentication and creating an administrative user.

Note: The related tutorials on how to configure the server, install, and then securely install MongoDB refer to Ubuntu 20.04. This tutorial focuses on MongoDB itself, not the underlying operating system. As long as authentication is enabled, it will generally work with any MongoDB installation regardless of the operating system.

Step 1 – Connect to MongoDB Server

To open a MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell that connects to a locally installed MongoDB instance running on port 27017.

Run the mongo command without any additional parameters:

mongo

This prints a welcome message with some information about the server the shell is connected to, as well as the version of MongoDB installed. The following example shows the MongoDB server running on 127.0.0.1 (a loopback interface representing localhost) on the default MongoDB port (27017) and version 4.4.6.

Output
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b9a48dc7-e821-4b09-a753-429eedf072c5") }
MongoDB server version: 4.4.6

Try to list all the databases on the server. After the shell command, type show dbs and press ENTER:

show dbs

Assuming you followed the prerequisite tutorial on How To Secure MongoDB, this command will not return any output. The reason for this is that, even though the MongoDB server is running and the shell was able to connect to it, you did not provide any authentication information. Because of this, you do not have any access rights to work with any of the server's databases, and the show dbs command will not return anything.

Exit by typing the following command:

exit

The Mongo shell prints a brief goodbye message and returns you to the system shell:

Output
bye

Note: Instead of typing the exit command, an alternative way to close the shell is to press CTRL+C instead.

Now connect the MongoDB shell to the database server again, but this time provide a username and password for proper authentication to your MongoDB instance. To do this, you need to provide additional command line parameters, as in the following example:

mongo -u AdminSammy -p --authenticationDatabase admin

This command consists of several parts:

  • -u: This flag sets the username used for authentication on the MongoDB server.
  • -p: This flag tells the MongoDB shell to use a password when connecting to the database. After pressing ENTER, you will be prompted to provide a password in the terminal window.
  • --authenticationDatabase: This option specifies the user authentication database you are logging in with. Typically, administrative accounts are managed in the admin database, but if your user authentication database is different, enter that database instead of admin.

Note: To connect to a MongoDB server running on a machine other than localhost, you can add the -h flag and then your server's IP address to the shell command.

Enter the password set during installation and you will have access to the shell once again.

Now run the show dbs command once again:

show dbs

This time, the command returns a list of all the databases on the system:

Output
admin 0.000GB
config 0.000GB
local 0.000GB

Because you are authenticated as a privileged user, the shell allows you to execute commands on any of these databases.

Now that you have successfully connected to the MongoDB server using the MongoDB shell, you can move on to learning how to run commands in the shell.

Step 2 – Execute the commands

Like other command-line interfaces, the MongoDB shell accepts commands and returns the desired results to standard output. As mentioned earlier, in the MongoDB shell, all commands are typed on the command line, which is indicated by a greater-than sign (>). Pressing ENTER after the command immediately executes it and returns the command output to the screen.

Most commands in a MongoDB database are executed on a selected database or set of databases. The currently selected database is represented by the db object accessible through the shell. You can check which database is currently selected by typing db in the shell:

db

In a newly connected shell instance, the selected database is always called test:

Output
test

You can safely use this database to test MongoDB and the MongoDB shell. To switch to another database, you can run the use command followed by the name of the new database. Try switching to a database called fruit:

use fruits

The shell will inform you that you are now using the new database:

Output
switched to db fruits

You can verify this by typing db again to find the currently selected database name:

db

This time, the output reflects the new database:

Output
fruits

Note that you did not explicitly create the fruits database. MongoDB allows you to execute commands on databases and collections that do not yet exist. It only creates these structures when an object is inserted into them for the first time. Even if you successfully change the current database to fruits, this database does not yet exist.

Try creating this database by inserting an object into it. The following example explains how to insert an object into a collection in the database called apples. By adding this object, the operation creates both the fruits database and the apples collection.

Type the following line in the MongoDB shell and press ENTER. Note the highlighted collection name (apples):

db.apples.insert()

Pressing ENTER after the opening parenthesis starts a multi-line command prompt, allowing you to enter longer commands on more than one line. The insert command is not fully entered until you enter a closing parenthesis. Until you do, the prompt changes from a greater-than sign to an ellipsis (…).

You don't need to split MongoDB commands into multiple lines like this, but doing so can make long commands easier to read and understand.

On the next line, enclose the object in a pair of brackets ({ and }). This sample document has only one field and value pair:

{name: 'Red Delicious'}

When you press ENTER again, another line will appear that allows you to add more command parameters, such as other documents or any specifications allowed by the MongoDB insert method. But for this example, you can end your input and execute the operation by entering a closing parenthesis and pressing ENTER.

This time, the Mongo shell records the end of the insert command and executes the entire command.

Output
WriteResult({ "nInserted" : 1 })

After inserting this new object into the database, both the fruits database and the apples collection will exist. Check the list of available databases with the show dbs command:

show dbs

Again, it returns a list of all available databases, but this time the list includes the fruits database:

Output
admin 0.000GB
config 0.000GB
fruits 0.000GB
local 0.000GB

The show collections command is useful for retrieving a list of collections in the currently selected database:

show collections

Since the fruits database is selected, it will only return the newly created collection of apples:

Output
apples

With this, you learned how to run commands in the MongoDB shell. You also created an instance object, which in turn created a new database and a new collection that now exists on the server.

In the final step of this guide, you will learn how to invoke MongoDB shell helper features to better understand commands and execute them more easily.

Step 3 – Get interactive help from the shell

The MongoDB shell has a built-in help system that you can use to get information about the available commands of the database system and the objects stored in it. This introductory help page can be viewed directly at the shell prompt with the help command:

help

The MongoDB shell returns a list of more detailed help entries that you can use for more information about specific parts of the shell, as well as with some examples of the most commonly used commands:

Output
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.mycoll.find() list objects in collection mycoll
db.mycoll.find( { a : 1 } ) list objects in mycoll where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell

The first two entries highlighted in the output of this example show how to run the helper command for the current database and a collection in the current database, respectively. The given example collection name is mycoll, but any valid collection name can be used.

The last highlighted line – db.mycoll.find() – is an example of a method for retrieving an object from a collection using the find command, which lists the objects in a given collection. Since collections are some of the most commonly used structures in a Mongo database, in this step we will examine how to use Mongo’s collection-level find() and help() methods.

First, access the apples package man page to find the commands available for this package:

db.apples.help()

Note: While the original help command was just help, when executing a helper method on database and collection objects, you must follow the command with a pair of parentheses so that it is read as help() and not just help.

The output of this command is a long list of available commands that you can perform on the apples collection:

Output
DBCollection help
db.apples.find().help() - show DBCursor help
db.apples.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.apples.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.apples.countDocuments( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
. . .
db.apples.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
e.g. db.apples.find( {x:77} , {name:1, x:1} )
db.apples.find(...).count()
db.apples.find(...).limit(n)
db.apples.find(...).skip(n)
db.apples.find(...).sort(...)
. . .

In addition to a clean list of available commands you can run in the db.apples collection (each followed by a short explanation of what the command does), this man page also provides examples of using commonly used commands such as find().

This on-board help system acts as a handy reference of available commands. You can use it to check your syntax if you can't remember the exact spelling or acceptable parts of a command.

Since you already learned from the man pages that find() can be used to retrieve objects from a collection, you can now retrieve the object created in the apples collection in the previous step.

However, this example highlights another interactive MongoDB helper known as command completion. The MongoDB shell follows the pattern found in other popular shells like Bash or zsh where pressing the TAB key on the keyboard automatically completes any command you are in the process of typing.

Start by typing the following, but don't press ENTER yet:

db.a

Instead of typing the full collection name, press the TAB key on your keyboard. The MongoDB shell responds with a list of all available possibilities, starting with the following:

Output
> db.a
db.adminCommand( db.aggregate( db.apples db.auth(

This output lists three commands, indicated by open parentheses, as well as the set apples.

Type another letter in the Shell:

db.ap

Press TAB once more. This time, there is no other option to start with ap and the MongoDB shell will autocomplete the input and type db.apples for you. Follow the same principle and complete the find() command using TAB completion. Type fi but do not press ENTER:

db.apples.fi

Pressing TAB will autocomplete the command name to db.apples.find. At this point, pressing TAB again will cause the shell to list more possibilities, but you can manually add a closing parenthesis to execute the find command:

db.apples.find()

The shell will display a list of all the objects in the apple collection. There will be only one object, the one you imported earlier:

Output
{ "_id" : ObjectId("60f31447f5643f739b0276e9"), "name" : "Red Delicious" }

Result

This article will introduce you to the MongoDB shell. The shell allows you to insert new objects into the database, query existing collections, and perform administrative tasks to manage the database, its data, and its users.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like