我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
当前回答
这个怎么样:
echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName
其他回答
把它放在一个名为test.js的文件中:
db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
print(collection);
});
然后用mongo myDbName test.js运行它。
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
谢谢printf!在Linux环境中,有一种更好的方法,可以只让一个文件运行。假设你有两个文件,蒙古cmds .js有多个命令:
use someDb
db.someColl.find()
然后运行驱动shell文件:runMongoCmds.sh
mongo < mongoCmds.js
更新版本的mongodb
mongosh < mongoCmds.js
相反,只有一个文件runMongoCmds.sh包含
printf "use someDb\ndb.someColl.find()" | mongo
Bash的printf比echo健壮得多,并且允许命令之间的\n强制它们在多行上。
遗留的mongo shell已从MongoDB中移除,并将于2022年发布第6版
有一种使用新shell mongosh执行shell脚本的新方法
来自编写脚本的shell文档:
您可以使用mongosh从命令行执行脚本,而无需进入mongosh控制台 要指定文件名,请使用——file或-f参数指定文件名 您可能还需要指定连接信息
你也可以使用——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 :