我想在shell脚本中执行mongo命令,例如在脚本test.sh中:

#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections

当我通过./test.sh执行这个脚本时,会建立到MongoDB的连接,但不会执行以下命令。

如何通过shell脚本test.sh执行其他命令?


当前回答

创建一个脚本文件;写命令:

#!/bin/sh
mongo < file.js

对于更新的版本 Mongosh < file.js

在file.js中编写mongo查询:

db.collection.find({"myValue":null}).count();

其他回答

关于这一点也有一个官方文档页面。

该页面的例子包括:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"

创建一个脚本文件;写命令:

#!/bin/sh
mongo < file.js

对于更新的版本 Mongosh < file.js

在file.js中编写mongo查询:

db.collection.find({"myValue":null}).count();
mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF

在我的设置中,我必须使用:

mongo --host="the.server.ip:port" databaseName theScript.js 

mongodb的更新版本

mongosh --host="the.server.ip:port" databaseName theScript.js 

如果你想用一条线来处理它,这是一个简单的方法。

file.sh --> db.EXPECTED_COLLECTION.remove("_id":1234)

cat file.sh | mongo <EXPECTED_COLLECTION>