我想在shell脚本中执行mongo命令,例如在脚本test.sh中:

#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections

当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。

如何通过shell脚本test.sh执行其他命令?


当前回答

这适用于我在Linux下:

mongo < script.js

mongodb的更新版本

mongosh < script.js

其他回答

正如tuxracer所建议的,你可以使用eval命令,对于那些像我一样缺少它的人,如果你不试图在默认db上执行form操作,你也可以添加你的db名称。

mongo <dbname> --eval "printjson(db.something.find())"

更新版本的mongodb

mongosh <dbname> --eval "printjson(db.something.find())"

这适用于我在Linux下:

mongo < script.js

mongodb的更新版本

mongosh < script.js

你也可以使用——eval标志对命令求值,如果它只是一个命令的话。

mongo --eval "printjson(db.serverStatus())"

请注意:如果你使用Mongo操作符,以$符号开始,你需要用单引号包围eval参数,以防止shell将操作符作为环境变量来计算:

mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName

否则你可能会看到这样的东西:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY    SyntaxError: Unexpected token :

把它放在一个名为test.js的文件中:

db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
  print(collection);
});

然后用mongo myDbName test.js运行它。

单shell脚本解决方案,能够传递mongo参数(——quiet, dbname,等):

#!/usr/bin/env -S mongo --quiet localhost:27017/test

cur = db.myCollection.find({});
while(cur.hasNext()) {
  printjson(cur.next());
}

-S标志可能不适用于所有平台。