MongoDB:缺失;带有 for 指令的 before 语句

Pho*_*ste 0 javascript mongodb

您好,我知道有一些关于此的问题,但我没有找到解决我的问题的方法。我的脚本在没有 for 循环的情况下工作正常,但是当它进入时,我遇到了 SyntaxError : Missing ; 声明之前...

这是我的脚本:

for (var i = 100; i < 301; ++i) {
    use F000 + i;
    var collections = db.getCollectionNames();
    collections.forEach(function(coll) {
        var c = db.getCollection(coll);
        c.remove({ date : { $lt : ISODate("2017-07-01T00:00:00.000Z") }});
    });
}
Run Code Online (Sandbox Code Playgroud)

感谢帮助我找到解决方案。

编辑:引发错误的行是:SyntaxError:缺失;声明之前 @(shell):1:32

Kev*_*ith 5

您需要使用这段代码切换数据库(use F000 + i;在您的示例中):

conn = new Mongo()
db = conn.getDB("dbname")
Run Code Online (Sandbox Code Playgroud)

或者如果您已经连接,则可以使用

db = db.getSiblingDB('dbname')
Run Code Online (Sandbox Code Playgroud)

use只是一个 shell 助手,在脚本中不起作用。

这里还有一些额外的阅读 - https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#differences- Between-interactive-and-scripted-mongo