如何通过shell脚本执行mongo命令? [英] How to execute mongo commands through shell scripts?
问题描述
我想在shell脚本中执行mongo
命令,例如在脚本test.sh
:
I want to execute mongo
commands in shell script, e.g. in a script test.sh
:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh
执行此脚本时,将建立与MongoDB的连接,但不会执行以下命令.
When I execute this script via ./test.sh
, then the connection to MongoDB is established, but the following commands are not executed.
如何通过Shell脚本test.sh
执行其他命令?
How to execute other commands through shell script test.sh
?
推荐答案
如果只是单个命令,也可以使用--eval
标志评估命令.
You can also evaluate a command using the --eval
flag, if it is just a single command.
mongo --eval "printjson(db.serverStatus())"
请注意::如果您使用的是Mongo运算符(以$符号开头),则需要将eval参数用单引号引起来,以防止外壳程序将运算符作为环境变量进行评估:
Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:
mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName
否则,您可能会看到以下内容:
Otherwise you may see something like this:
mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY SyntaxError: Unexpected token :
这篇关于如何通过shell脚本执行mongo命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!