我想在 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/