Docs HomeMongoDB Shell

Include External Files and Modules in Scripts在脚本中包括外部文件和模块

Important

A complete description of Node.js, modules, and the require() function is out of scope for this tutorial. Node.js、模块和require()函数的完整描述超出了本教程的范围。To learn more, see the Node.js Documentation.要了解更多信息,请参阅Node.js文档

To use files and modules in your mongosh interactions, use the require() function.要在mongosh交互中使用文件和模块,请使用require()函数。

In your mongosh scripts, you can require:在您的mongosh脚本中,您可以要求:

  • Local files本地文件
  • Built-in Node.js modules内置Node.js模块
  • External (npm) Node.js modules外部(npm)Node.js模块

Require a Local File需要本地文件

You can use JavaScript files in mongosh scripts without any additional setup or configuration.您可以在mongosh脚本中使用JavaScript文件,而无需任何额外的设置或配置。

Note

mongosh does not execute files imported with require(). Instead, mongosh adds everything from an imported file to the current execution scope.mongosh不执行使用require()导入的文件。相反,mongosh将从导入的文件到当前执行范围的所有内容都添加进去。

Example

To include a file named test.js that is located in the current working directory, use one of the following commands:要包含位于当前工作目录中的名为test.js的文件,请使用以下命令之一:

require('./tests.js')
var tests = require('./tests.js')

Require a Built-In Module需要内置模块

You can require built-in Node.js modules (such as fs) in mongosh without any additional setup or configuration.您可以在mongosh中要求内置Node.js模块(如fs),而无需任何额外的设置或配置。

Example

The following example creates and executes a script that:以下示例创建并执行一个脚本:

  • Connects to a local deployment running on the default port.连接到在默认端口上运行的本地部署。
  • Populates the myDatabase.employees collection with sample data.使用示例数据填充myDatabase.employees集合。
  • Uses the fs module to write a document from the myDatabase.employees collection to a file named employee.json.使用fs模块将myDatabase.employees集合中的文档写入名为employee.json的文件。
  1. Create a file named employee-to-text-file.js with the following contents:创建一个名为employee-to-text-file.js的文件,包含以下内容:

    const fs = require('fs');

    db = connect('mongodb://localhost/myDatabase');

    db.employees.insertMany( [
    { "name": "Alice", "department": "engineering" },
    { "name": "Bob", "department": "sales" },
    { "name": "Carol", "department": "finance" }
    ] )

    const document = db.employees.findOne();

    fs.writeFileSync('employee.json', JSON.stringify(document));
  2. To load and execute the employee-to-text-file.js file, run the following command from mongosh:要加载并执行employee-to-text-file.js文件,请从mongosh运行以下命令:

    load("employee-to-text-file.js")
  3. To confirm that the data was written to the file, open the employee.json file.要确认数据已写入文件,请打开employee.json文件。

Require an npm Module需要npm模块

You can require Node.js modules (such as those downloaded from npm). 您可以需要Node.js模块(例如从npm下载的模块)。To use external modules, you must install the modules either:要使用外部模块,必须安装以下模块之一:

  • Globally全局
  • In the node_modules directory in your current working directory.在当前工作目录的node_modules目录中。
Tip

You can require remote npm modules using this construction:您可以使用以下构造要求远程npm模块:

const localRequire = require('module').createRequire(__filename);)

For an example, see index.js in the resumetoken snippet.例如,请参阅resumetoken片段中的index.js

Example
Important

To run this example, you must install the date-fns module either globally or in the node_modules directory in your current working directory.要运行此示例,必须全局或在当前工作目录的node_modules目录中安装date-fns模块。

The following example creates and executes a script that:以下示例创建并执行一个脚本:

  • Connects to a local deployment running on the default port.连接到在默认端口上运行的本地部署。
  • Populates the myDatabase.cakeSales collection with sample data.使用示例数据填充myDatabase.cakeSales集合。
  • Uses the date-fns module to format dates.使用date-fns模块格式化日期。
  1. Create a file named date-fns-formatting.js with the following contents:创建一个名为date-fns-formatting.js的文件,其中包含以下内容:

    const formatDistance = require('date-fns/formatDistance')

    db = connect('mongodb://localhost/myDatabase');

    db.cakeSales.insertMany( [
    { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
    state: "CA", price: 13, quantity: 120 },
    { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
    state: "WA", price: 14, quantity: 140 },
    { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
    state: "CA", price: 12, quantity: 145 },
    { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
    state: "WA", price: 13, quantity: 104 },
    { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
    state: "CA", price: 41, quantity: 162 },
    { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
    state: "WA", price: 43, quantity: 134 }
    ] )

    const saleDate0 = db.cakeSales.findOne( { _id: 0 } ).orderDate
    const saleDate1 = db.cakeSales.findOne( { _id: 1 } ).orderDate

    const saleDateDistance0 = formatDistance(saleDate0, new Date(), { addSuffix: true })
    const saleDateDistance1 = formatDistance(saleDate1, new Date(), { addSuffix: true })

    print("{ _id: 0 } orderDate was " + saleDateDistance0)
    print("{ _id: 1 } orderDate was " + saleDateDistance1)
  2. To load and execute the date-fns-formatting.js file, run the following command from mongosh:要加载并执行date-fns-formatting.js文件,请从mongosh运行以下命令:

    load("date-fns-formatting.js")

    mongosh outputs something like the following:输出如下内容:

    { _id: 0 } orderDate was over 1 year ago
    { _id: 1 } orderDate was 7 months ago

    Your output may vary depending on the date that you run the example.您的输出可能因运行示例的日期而异。