对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
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.

有多种方法可以将环境变量从文件加载到脚本。此示例使用内置的loadEnvFile() 函数,该函数将变量从 .env文件加载到应用程序的环境中。

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