我想在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执行其他命令?
当前回答
mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF
其他回答
下面的shell脚本也很适合我……definite不得不使用Antonin一开始提到的重定向…这让我产生了测试这里文档的想法。
function testMongoScript {
mongo <<EOF
use mydb
db.leads.findOne()
db.leads.find().count()
EOF
}
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
如果您已启用身份验证:
mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
更新版本
mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js
mongo <<EOF
use <db_name>
db.getCollection("<collection_name>").find({})
EOF
如果你想用一条线来处理它,这是一个简单的方法。
file.sh --> db.EXPECTED_COLLECTION.remove("_id":1234)
cat file.sh | mongo <EXPECTED_COLLECTION>