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

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

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

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


当前回答

如果您已启用身份验证:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js

更新版本

mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js

其他回答

这适用于我在Linux下:

mongo < script.js

mongodb的更新版本

mongosh < script.js

如果您已启用身份验证:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js

更新版本

mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js

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

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

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

创建一个脚本文件;写命令:

#!/bin/sh
mongo < file.js

对于更新的版本 Mongosh < file.js

在file.js中编写mongo查询:

db.collection.find({"myValue":null}).count();

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

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

更新版本的mongodb

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