How to use the `mongosh` command (with examples)

How to use the `mongosh` command (with examples)

mongosh is the modern shell interface for MongoDB, designed to provide an enhanced user experience over the older mongo shell. It allows users to connect to MongoDB databases, perform administrative tasks, and execute JavaScript directly against the database. Whether you’re managing databases locally or remotely, mongosh offers a versatile command-line environment for interacting with MongoDB.

Connect to a local database on the default port (mongodb://localhost:27017):

Code:

mongosh

Motivation:

Connecting to a local MongoDB server is a common initial step for developers and database administrators who want to interact with their databases on a development machine or testing environment. This simple command leverages default settings to quickly establish a connection to the database server running locally, making it ideal for quick access without specifying additional options.

Explanation:

  • mongosh: This invokes the MongoDB shell program. By itself, it assumes you want to connect to a MongoDB instance running locally on the machine (localhost) using the default port number (27017). This is typically the standard configuration for a local MongoDB server installation.

Example Output:

When you run this command, you’ll see a connection initiation message, including details about the MongoDB server version and environment, followed by the MongoDB shell prompt, ready for interaction:

Current Mongosh Log ID: 1234567890abcdef
Connecting to: mongodb://localhost:27017
MongoServer version: 5.0.2
MongoDB Enterprise 𝐧 𝐞
>

Connect to a database:

Code:

mongosh --host host --port port db_name

Motivation:

Connecting to a specific MongoDB instance, whether on a different host, port, or database, is necessary when working on production environments, hosting services, or distributed applications. In such scenarios, database administrators need precise connection configurations to access particular databases securely and efficiently.

Explanation:

  • --host host: Specifies the hostname or IP address of the MongoDB server. This is essential when the MongoDB server is not located on the local machine, allowing developers to remotely manage databases.

  • --port port: Indicates the port number on which the MongoDB server is listening. This is particularly useful for instances where MongoDB is configured to use a non-standard port.

  • db_name: This is the name of the database you wish to connect to. It directs mongosh to focus operations on this specific database once connected.

Example Output:

After executing the command, you connect to the specified remote database, and it provides a similar prompt as a local connection, confirming the server’s identity:

Current Mongosh Log ID: abcdef1234567890
Connecting to: mongodb://host:port
MongoServer version: 4.4.8
switched to db db_name
>

Authenticate using the specified username on the specified database:

Code:

mongosh --host host --port port --username username --authenticationDatabase authdb_name db_name

Motivation:

Authentication is a critical aspect of database security, particularly in environments where sensitive or restricted data is handled. This command enables secure access through identity verification, allowing authorized users to perform operations on the database without exposing sensitive credentials in the command-line interface.

Explanation:

  • --host host: Designates the server’s hostname or IP address, ensuring the connection targets the correct MongoDB instance.

  • --port port: The port number used to reach the specific MongoDB server instance.

  • --username username: The username to authenticate the connection. This prompts for a password, ensuring that credentials are not exposed in the command history.

  • --authenticationDatabase authdb_name: Specifies the database that stores the authentication details, which may differ from the target database. This argument tells MongoDB where to verify credentials.

  • db_name: Denotes the database you want to interact with once authenticated.

Example Output:

Upon executing, you’ll be prompted for a password. Once provided and authenticated, the shell connects, and you are ready for database operations:

Enter password:
Current Mongosh Log ID: 0987654321fedcba
Connecting to: mongodb://host:port
MongoServer version: 4.2.14
switched to db db_name
>

Evaluate a JavaScript expression on a database:

Code:

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

Motivation:

Sometimes, it’s necessary to execute quick queries or test JavaScript within MongoDB for various tasks like verifying data structures, debugging scripts, or retrieving sample data. The --eval option allows direct execution of JavaScript expressions within the MongoDB shell without requiring an interactive session, streamlining such tasks.

Explanation:

  • --eval '...': Executes a JavaScript expression directly from the shell command line. This can be highly beneficial for scripting and automation as it produces immediate evaluation and results.

  • JSON.stringify(db.foo.findOne()): A JavaScript snippet that fetches one document from the foo collection in the database, formats it as a JSON string for readability and output.

  • db_name: Identifies the database containing the foo collection from which the document retrieval is to take place.

Example Output:

This command fetches a document and outputs its JSON representation, helping users to immediately view or verify the data:

"{\"_id\":\"60e1bae85e6110a194c09574\",\"name\":\"sample document\",\"value\":123}"

Conclusion:

The mongosh command-line tool is an essential utility for MongoDB users, offering streamlined and versatile options for connecting to, authenticating with, and operating on MongoDB databases. Each use case illustrates how mongosh can simplify common database tasks and support secure, efficient database management, whether working locally or remotely. With its capability to execute JavaScript directly, it also provides a powerful toolset for rapid database scripting and automation.

Related Posts

How to Use the Command 'qm guest exec-status' (with examples)

How to Use the Command 'qm guest exec-status' (with examples)

The qm guest exec-status command is an essential tool for administrators managing QEMU/KVM virtual machines via the Proxmox Virtual Environment (PVE).

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

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

The xbacklight command is a powerful utility for users running the X Window System, particularly useful in managing the brightness of a laptop or desktop screen.

Read More
Let a Steam Locomotive Run Through Your Terminal (with Examples)

Let a Steam Locomotive Run Through Your Terminal (with Examples)

The sl command is a whimsical tool designed to inject a bit of humor and levity into the often serious world of command-line programming.

Read More