How to use the command 'mongo' (with examples)

How to use the command 'mongo' (with examples)

The mongo command is an interface for connecting and interacting with MongoDB databases. Although it is referred to as the legacy MongoDB shell, it remains a useful tool for database administrators and developers who need to manage and query MongoDB databases. The command provides options for connecting to different databases, authenticating users, and executing JavaScript expressions on the database. This article provides examples of using the mongo command, illustrating its use cases.

Use case 1: Connect to a local database on the default port

Code:

mongo

Motivation:

This use case is ideal when you want to connect to a MongoDB instance running on your local machine using the default port, which is 27017. It’s a quick way to access the database without specifying additional connection parameters, useful during development or for initial exploration of a local MongoDB setup.

Explanation:

  • mongo: This is the command to launch the MongoDB shell.

Since no additional parameters are provided, the command assumes you want to connect to a database at the default host (localhost) and port (27017). This simplifies access to MongoDB when running locally.

Example output:

Upon executing the mongo command, you may see an output indicating a successful connection, the version information for MongoDB, and the shell prompt waiting for further commands:

MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
>

Use case 2: Connect to a database

Code:

mongo --host host --port port db_name

Motivation:

You may need to connect to a remote MongoDB database instance running on a different server or port. By specifying the host, port, and database name, you ensure you are accessing the correct MongoDB instance and database, crucial for scenarios where multiple instances are in play, like production environments.

Explanation:

  • --host host: Specifies the hostname or IP address of the MongoDB server where the database is hosted.
  • --port port: Indicates the port on which the MongoDB server is listening for connections.
  • db_name: The name of the database you are targeting within the MongoDB server.

These parameters help establish a connection to the desired database instance, ensuring proper communication across networks.

Example output:

After executing the command with correct parameters, the shell connects to the specific MongoDB instance and indicates readiness for further operations:

MongoDB shell version v3.6.3
connecting to: mongodb://host:port/db_name
MongoDB server version: 3.6.3
>

Use case 3: Authenticate using the specified username on the specified database

Code:

mongo --host host --port port --username username --authenticationDatabase authdb_name db_name

Motivation:

In environments requiring secure access, authentication is paramount. This use case is applicable when a database requires credentials for access, allowing you to specify a username and an authentication database to validate the session. It is essential in production scenarios with strict access controls.

Explanation:

  • --host host: Specifies the host where the MongoDB server resides.
  • --port port: Indicates the port on which the server is accessible.
  • --username username: The user account’s username required for authentication.
  • --authenticationDatabase authdb_name: The specific database that contains user credentials and where authentication occurs.
  • db_name: The name of the database you wish to connect to, assuming authentication was successful.

These arguments together handle securely logging into a secured MongoDB environment, ensuring only authorized users can perform operations.

Example output:

After running the command, you’ll be prompted for a password and, upon successful authentication, you’ll be welcomed into the database shell:

MongoDB shell version v3.6.3
Enter password: 
connecting to: mongodb://host:port/db_name
MongoDB server version: 3.6.3
>

Use case 4: Evaluate a JavaScript expression on a database

Code:

mongo --eval 'JSON.stringify(db.foo.findOne())' db_name

Motivation:

The ability to execute JavaScript expressions directly on a MongoDB database through the shell is extremely powerful. It’s especially useful for database administrators and developers needing to quickly query or manipulate data without writing full-fledged scripts. This use case demonstrates how to retrieve the first document from a collection using an inline JavaScript expression.

Explanation:

  • --eval 'JSON.stringify(db.foo.findOne())': Directly evaluates a JavaScript expression within the connected database context. The db.foo.findOne() part queries the first document from the collection foo, and JSON.stringify() converts the result into a JSON-formatted string.
  • db_name: The database against which to execute the JavaScript evaluation.

This approach provides rapid access to data and the ability to manipulate it in real-time, facilitating quick diagnostics and testing.

Example output:

Executing this command will output the JSON representation of the first document found in the foo collection, such as:

{ "_id" : ObjectId("507f1f77bcf86cd799439011"), "name" : "example document" }

Conclusion:

The mongo command offers versatile functionality for connecting to, querying, and interacting with MongoDB databases. Through these examples, we demonstrated practical applications of the command in scenarios ranging from simple local connections to authenticating against remote databases and leveraging JavaScript for data manipulation. Understanding these use cases enhances the user’s ability to manage MongoDB environments efficiently.

Related Posts

How to use the command 'partx' (with examples)

How to use the command 'partx' (with examples)

The partx command is a powerful utility primarily used for parsing partition tables and transferring the details to the Linux kernel.

Read More
How to use the command 'xxd' (with examples)

How to use the command 'xxd' (with examples)

The xxd command is a powerful utility available on Unix-like systems, primarily used for creating hexadecimal representations (hexdumps) from binary files and for reversing hexdumps back into their original binary form.

Read More
How to Use the Command 'jwt' (with Examples)

How to Use the Command 'jwt' (with Examples)

The jwt command-line tool is designed to work with JSON Web Tokens (JWTs), a compact and URL-safe means of representing claims transferred between two parties.

Read More