For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Use Environment Variables in MongoDB Shell Scripts

You can use environment variables in your MongoDB Shell scripts to manage configuration settings and store sensitive information outside of your source code. For example, environment variables let you store database connection strings, API keys, and other parameters outside of your main scripts.

In the following example, you will learn how to use an environment variable for your MongoDB connection string.

There are multiple ways to load environment variables from a file into your script. This example uses the built-in loadEnvFile() function, which loads variables from an .env file into your application's environment.

1

In an empty directory, create a new file named .env.

2

In the .env file, define an environment variable for your MongoDB connection string:

MONGODB_URI="<connection-string>"
3

In the same directory as your .env file, create a script called myScript.js and populate it with the following contents:

// Load environment variables from the .env fileconst { loadEnvFile } = require('node:process');loadEnvFile(); // Connect to the MongoDB databasedb = connect(process.env.MONGODB_URI); // Confirm the connection by printing the database nameconsole.log(db);

The script uses the process.env object to access your connection string environment variable.

4

The script outputs the name of the database you connected to. The default database is test.

mongosh --file myScript.js
test
Rate this page