How do I use MongoDB shell

Introduction to the

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 this case, you are not interacting directly with the database server. However, direct access may be required to perform administrative tasks on the database or to perform temporary database queries yourself.

That’s what _MongoDB shell_ does. MongoDB Shell is an interactive console that you can use to connect to and execute commands on a database server, allowing you to perform administrative tasks and read, write, or manipulate data directly. MongoDB shell enables you to connect to a database from a command line prompt and interactively process it from a terminal window. It also allows you to run external scripts to perform repetitive tasks more easily.

In this tutorial, you’ll use the MongoDB shell to connect to and interactively query a MongoDB database. You’ll also use the built-in help system and auto-complete features included in the shell.

The premise condition

To follow this tutorial, you will need.

  • One has common users, non-root users, and hassudoPermission server, and a firewall configured with UFW. This tutorial is verified using a server running Ubuntu 20.04, which you can followUbuntu 20.04 initial server setup tutorialTo prepare your server.
  • Install MongoDB on your server. To set this up, follow our tutorial: How to install MongoDB on Ubuntu 20.04.
  • The MongoDB instance of your server is secured by enabling authentication and creating an administrative user. To secure MongoDB like this, follow our tutorial: How to secure MongoDB on Ubuntu 20.04.

Note: The linked tutorial on how to configure the server, install and secure the MongoDB installation refers to Ubuntu 20.04. This tutorial focuses on MongoDB itself, not the underlying operating system. It generally works with any MongoDB installation, regardless of operating system, as long as authentication is enabled.

Step 1 – Connect to the MongoDB server

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

Try running the mongo command with no other arguments.

mongo
Copy the code

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

OutputMongoDB shell version v4.4.6 connecting to: mongo: / / 127.0.0.1:27017 /? compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID(" b9a48dc7-e821-4B09-A753-429EEDf072C5 ")} MongoDB server version: 4.4.6Copy the code

Below this information, the MongoDB shell prompt — indicated by a greater-than sign — appears.

Try to list all the databases available on the server. Type show DBS after the shell prompt, and then press ENTER.

show dbs
Copy the code

Assuming you followed the previous tutorial in How to Protect MongoDB, this command does not return any output. The reason is that even though the MongoDB server is running and the shell is able to connect to it, you don’t provide any authentication information. Because of this, you do not have access to any server database, and the show DBS command does not return any results.

Exit the shell by typing.

exit
Copy the code

Mongo Shell will print a short farewell message and return you to the system shell.

Outputbye
Copy the code

Note: Another way to close the shell without entering the exit command is to press CTRL + C.

Now try to reconnect the MongoDB shell to the database server, but this time provide a username and password to properly authenticate your MongoDB instance. To do this, you need to provide additional command-line arguments, as shown in the following example.

mongo -u AdminSammy -p --authenticationDatabase admin
Copy the code

This command consists of several parts.

  • -u: this flag sets the username used to authenticate access to the MongoDB server. This example specifies wherePrerequisites MongoDB security TutorialTo create an administrative user,AdminSammy. In this tutorial, if you have a different admin user, you can replace it with your own admin user username.
  • -p: this flag tells the MongoDB shell to use a password when connecting to the database. In the pressENTERAfter that, the terminal window will prompt you for a password.
  • --authenticationDatabase: This option specifies the authentication database for the user you want to log in to. Normally, the managed account is inadminThe database is managed, but if your user’s authentication database is different, please enter that database insteadadmin

Note: To connect to a MongoDB server running on a different machine than localhost, you can add the -h flag to your shell command, followed by your server’s IP address.

Enter the password you set when you install, and you’ll get access to the shell again.

Now try the show DBS command again.

show dbs
Copy the code

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

Outputadmin   0.000GB
config  0.000GB
local   0.000GB
Copy the code

Because you have been authenticated as a privileged user, the shell will allow you to run commands from any of these databases.

Now that you have successfully connected to the MongoDB server using the MongoDB shell, you can continue to learn how to execute commands in the shell.

Step 2 – Execute commands

Like any other command line interface, the MongoDB shell accepts commands and returns the desired results to standard output. As mentioned earlier, in MongoDB shell, all commands are entered into a command prompt denoted by a greater-than sign (>). After you press ENTER, the command is immediately executed and the command output is returned to the screen.

Most commands in a MongoDB database are executed on a database or a collection of selected databases. The currently selected database is represented by a DB object accessed through the shell. You can check the currently selected database by typing DB in the shell.

db
Copy the code

In a newly connected shell instance, the selected database is always called Test.

Outputtest
Copy the code

You can safely use this database to experiment with MongoDB and MongoDB shell. To switch to another database, you can run the use command followed by the new database name. Try switching to a database called FRUITS.

use fruits
Copy the code

The shell notifies you that you are now using a new database.

Outputswitched to db fruits
Copy the code

You can verify this by typing DB again to find the name of the currently selected database.

db
Copy the code

This time, the output will reflect the new database.

Outputfruits
Copy the code

Note that you are not explicitly creating the FRUITS database. MongoDB allows you to run commands on databases and collections that don’t yet exist; It creates these structures only when the object is first inserted. Even if you successfully switch your current database to FRUITS, it doesn’t exist yet.

Try to create the database by inserting an object into it. The following example Outlines how to insert an object into a collection called Apples in a database. By adding this object, this operation creates both the FRUITS database and the Apples collection.

Type the following line in MongoDB shell, and then press ENTER. Notice the collection name (apples) highlighted.

db.apples.insert(
Copy the code

Pressing ENTER after an open bracket launches a multi-line command prompt that allows you to type longer commands on multiple lines. Insert is not registered as complete until you enter closing parentheses. Before you do this, the prompt changes from greater than sign to ellipsis (…). .

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

On the next line, enter the objects ({and}) inside a pair of braces. The example file has only one field and value pair.

{name: 'Red Delicious'}
Copy the code

When you press ENTER again, another line prompts you to add further command parameters, such as other files or whatever specifications MongoDB’s INSERT method allows. But for this example, you can finish typing and run the operation by entering a closing parenthesis and pressing ENTER.

)
Copy the code

At this point, Mongo shell registers the end of the INSERT command and executes the entire statement.

OutputWriteResult({ "nInserted" : 1 })
Copy the code

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
Copy the code

Again, this will return a list of all available databases, but this time the list includes fruits database.

Outputadmin   0.000GB
config  0.000GB
fruits  0.000GB
local   0.000GB
Copy the code

To retrieve the list of collections available in the currently selected database, the show Collections command comes in handy.

show collections
Copy the code

Because the FRUITS database is selected, it will only return the newly created apples collection.

Outputapples
Copy the code

That’s it. You’ve learned how to execute commands in the MongoDB shell. You also create a sample object, which in turn creates a new database and a new collection, which is now persisted on the server.

In the final step of this tutorial, you’ll learn how to invoke MongoDB shell’s help feature 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 and objects stored in the database system. This introductory help screen can be accessed directly at the shell prompt with the help command.

help
Copy the code

MongoDB Shell returns a more detailed list of help items that you can use to learn more about specific parts of the shell, as well as examples of some 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 shellCopy the code

The first two items highlighted in the output of this example illustrate how to execute help for the current database and a collection in the current database, respectively. The sample collection name given is Mycoll, but any valid collection name can be used.

The last highlighted line – db.mycol.find () – is an example of retrieving objects from a collection using the find command, which lists the objects in a given collection. Because collections are some of the most commonly used structures in Mongo databases, this step shows you how to use Mongo’s find() and help() collection-level methods.

First, visit the Help screen for the Apples collection to find the commands available for this collection.

db.apples.help()
Copy the code

** Note: ** Although the initial help command is just help, when executing the _ help method _ on database and collection objects, you must enclose a pair of parentheses after the command so that it is read as help(), not just help.

The output of this command will be a lengthy list of available commands that you can execute on the Apples collection.

OutputDBCollection 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(...)
. . .
Copy the code

In addition to a pure list of available commands that you can execute on the db.Apples collection (each followed by a short description of the given command), the help screen also gives examples of frequently used commands, such as find().

The bundled help system serves as a useful reference to the commands available. You can use it to check your grammar in case you can’t remember the exact spelling or acceptable fields of a command.

Since you already know from the help screen that find() can be used to retrieve objects from a collection, you can now try to retrieve the objects you created in the Apples collection in the previous step.

However, this example will highlight another of MongoDB’s interactive help tools, the _ command completion _. MongoDB shell follows the pattern found in other popular shells such as Bash or ZSH, and pressing TAB on the keyboard will automatically complete whatever command you are typing.

Start typing the following, but don’t press ENTER yet.

db.a
Copy the code

Instead of entering the full name of the collection, press TAB on your keyboard. MongoDB shell will respond with a list of all available possibilities starting with a.

Output> db.a
db.adminCommand(  db.aggregate(     db.apples         db.auth(
Copy the code

This output lists the three commands, represented by a starting bracket, and the collection of apples.

Type one more letter in the shell.

db.ap
Copy the code

Press TAB again. This time, there is no other possibility to start with AP, and MongoDB Shell will automatically complete the entry by typing db.apples for you. Following the same principle, use TAB to complete the find() command. Type fi, but don’t press ENTER.

db.apples.fi
Copy the code

Pressing TAB automatically completes the command name to db.apples. Find. At this point, pressing TAB again causes the shell to list more possibilities, but you can manually add a closing bracket to execute the find command.

db.apples.find()
Copy the code

The shell displays a list of all the objects found in the Apples collection. There will only be one object here, the one you inserted earlier.

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

Just like that, you’ve learned how to use the built-in help system and Mongo Shell’s auto-complete feature.

conclusion

By reading this article, you are already familiar with the MongoDB shell. With the shell, you can insert new objects into the database, query existing collections, and perform administrative tasks that manage the database, its data, and users.

MongoDB shell has direct access to most of Mongo’s functionality, such as database and collection objects and methods, making it the primary tool for interacting with database servers. However, the same capabilities and methods are available when using MongoDB programmatically, either through MongoDB shell scripts or through the drivers that MongoDB provides for many programming languages.

You can follow the principles described in this tutorial to execute commands in the MongoDB shell from other articles in this series. We encourage you to find out more about the MongoDB Shell in the official MongoDB documentation.