【问题标题】:How to run a javascript file inside a mongo shell after connection连接后如何在 mongo shell 中运行 javascript 文件
【发布时间】:2017-05-04 00:13:50
【问题描述】:

我有一个 javascript 文件并想在 mongo shell 中运行它们。我知道如何在连接期间从这个链接加载 javascript 文件:How to execute mongo commands through shell scripts?。 但我的情况是如何在连接建立后运行外部 js 文件。

我的 js 文件如下所示:

db.getSiblingDB("test")
  .enron_messages.find({
    $or: [{ filename: "111." }, { "headers.From": "test@gmail.com" }]
  })
  .sort({ "headers.To": 1 })
  .limit(10);

在我的 mongo shell 中,我使用 load('test.js') 加载该文件,但它返回 true(见下面的输出)。这个文件如何执行?

> load('test.js')
true

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    load() 函数实际上执行了 javascript 文件。您面临的问题是,当外部脚本在“脚本化”模式下执行时,find() 只会返回光标,而不是像在 Interactive mode 中运行时那样迭代它的 mongo shell。

    Write Scripts for the Mongo shell 中的文档详细介绍了此行为。在那里,您将看到一个如何迭代光标并打印结果的示例:

    cursor = db.collection.find();
    while ( cursor.hasNext() ) {
        printjson( cursor.next() );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      相关资源
      最近更新 更多