如何通过shell脚本执行mongo命令? [英] How to execute mongo commands through shell scripts?

查看:1111
本文介绍了如何通过shell脚本执行mongo命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆