我想在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执行其他命令?
当前回答
这个怎么样:
echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName
其他回答
这个怎么样:
echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName
在我的设置中,我必须使用:
mongo --host="the.server.ip:port" databaseName theScript.js
mongodb的更新版本
mongosh --host="the.server.ip:port" databaseName theScript.js
——shell标志也可以用于javascript文件
mongo --shell /path/to/jsfile/test.js
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF