我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
我想在shell脚本中执行mongo命令,例如在脚本test.sh中:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。
如何通过shell脚本test.sh执行其他命令?
当前回答
在我的情况下,我可以方便地使用\n作为分隔符的下一个mongo命令,我想要执行,然后管道他们到mongo
echo $'use your_db\ndb.yourCollection.find()' | mongo
更新版本的mongodb
echo $'use your_db\ndb.yourCollection.find()' | mongosh
其他回答
如果你想用一条线来处理它,这是一个简单的方法。
file.sh --> db.EXPECTED_COLLECTION.remove("_id":1234)
cat file.sh | mongo <EXPECTED_COLLECTION>
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
你也可以使用——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 :
这适用于我在Linux下:
mongo < script.js
mongodb的更新版本
mongosh < script.js
在我的情况下,我可以方便地使用\n作为分隔符的下一个mongo命令,我想要执行,然后管道他们到mongo
echo $'use your_db\ndb.yourCollection.find()' | mongo
更新版本的mongodb
echo $'use your_db\ndb.yourCollection.find()' | mongosh