我想在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执行其他命令?
当前回答
把它放在一个名为test.js的文件中:
db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
print(collection);
});
然后用mongo myDbName test.js运行它。
其他回答
谢谢printf!在Linux环境中,有一种更好的方法,可以只让一个文件运行。假设你有两个文件,蒙古cmds .js有多个命令:
use someDb
db.someColl.find()
然后运行驱动shell文件:runMongoCmds.sh
mongo < mongoCmds.js
更新版本的mongodb
mongosh < mongoCmds.js
相反,只有一个文件runMongoCmds.sh包含
printf "use someDb\ndb.someColl.find()" | mongo
Bash的printf比echo健壮得多,并且允许命令之间的\n强制它们在多行上。
如果您已启用身份验证:
mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
更新版本
mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js
——shell标志也可以用于javascript文件
mongo --shell /path/to/jsfile/test.js
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
}