gpt4 book ai didi

mongodb - 如何通过shell脚本执行mongo命令?

转载 作者:IT老高 更新时间:2023-10-28 11:10:48 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com