使用mongo shell 执行JavaScript 函数没有输出

Executing JavaScript function with mongo shell has no output

这是我要执行的 JavaScript 函数:

var collectionCreation = function(){
  db.myFirstCollection.find();
};
collectionCreation();

从我的命令提示符指向 bin 目录,我想执行包含上述代码的 js 文件。我正在尝试按如下方式进行:

mongo localhost:27017/myFirstDatabase G:\MongoDB\createColl.js

它没有显示任何输出。我期待在我的 collection 中获得文件。请帮忙。提前致谢。

问题是您期望的结果与您在 REPL when you type db.myFirstCollection.find(), but that's not what happens here. As stated it's a REPL 中看到的结果相同,这意味着除非另外分配给变量或在本例中,语句被评估为“左侧”,否则,“在一个函数中。

所以简单地做一些事情来实际“打印”输出:

var collectionCreation = function(){
  db.myFirstCollection.find().forEach(printjson)
};
collectionCreation();

您在 shell db.myFirstCollection.find() 中看到的实际上是 Cursor 的“左手赋值”,然后对其求值并迭代前 20 个结果。

您同样可以通过以下方式阻止这种情况立即发生:

var cursor = db.myFirstCollection.find()

在您“评估”之前不会“打印”这些结果:

cursor

然后会打印出接下来的20个,这是默认的评价。

所以当你“编写脚本”时,你实际上需要对返回的 Cursor 结果做一些事情。在这种情况下 forEach() 每次迭代的结果和 printjson

如果您打算“玩转”更多此类内容,那么我建议您阅读 Write Scripts for the mongo Shell and also Iterate a Cursor in the mongo Shell within the core documentation. These cover most of the differences you would encounter as you work with "scripting" as compared to the "interactive" form as you simply type things into the REPL,其中 mongo shell 是。


快速演示

创建文件 test.js

(function() {
  db.test.remove({});
  db.test.insertMany([1,2,3].map(n => ({ n })));
})()

var listtest = function() {
  db.test.find().forEach(printjson)
}
listtest();

然后简单地在默认的“test”数据库命名空间上执行:

mongo --quiet test.js

Returns:

{ "_id" : ObjectId("5b13b91a71a13254af4e278e"), "n" : 1 }
{ "_id" : ObjectId("5b13b91a71a13254af4e278f"), "n" : 2 }
{ "_id" : ObjectId("5b13b91a71a13254af4e2790"), "n" : 3 }

请注意,以同样的方式,deleteMany()insertMany() 响应也通过包裹在内部函数中而被抑制,因此它们的结果不会被“左评估”。