Docs 菜单
Docs 主页
/ /

在MongoDB Shell脚本中使用环境变量

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

在空目录中,创建名为 .env 的新文件。

2

.env文件中,为MongoDB连接字符串定义一个环境变量:

MONGODB_URI="<connection-string>"
3

在与 .env文件相同的目录中,创建一个名为 myScript.js 的脚本并使用以下内容填充该脚本:

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

该脚本使用 process.env对象访问权限连接字符串环境变量。

4

该脚本会输出您连接到的数据库的名称。默认数据库为 test

mongosh --file myScript.js
test
  • 在脚本中包含外部文件和模块

  • 代码范围

  • Snippets

后退

require() 与 load()

在此页面上