我想在shell脚本中执行mongo
命令,例如在脚本test.sh
中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过
./test.sh
执行此脚本时,将建立与MongoDB的连接,但不会执行以下命令。如何通过shell脚本
test.sh
执行其他命令? 最佳答案
如果只是单个命令,也可以使用--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 :
关于mongodb - 如何通过Shell脚本执行mongo命令?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4837673/