我想在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执行其他命令?
当前回答
创建一个脚本文件;写命令:
#!/bin/sh
mongo < file.js
对于更新的版本 Mongosh < file.js
在file.js中编写mongo查询:
db.collection.find({"myValue":null}).count();
其他回答
——shell标志也可以用于javascript文件
mongo --shell /path/to/jsfile/test.js
下面的shell脚本也很适合我……definite不得不使用Antonin一开始提到的重定向…这让我产生了测试这里文档的想法。
function testMongoScript {
mongo <<EOF
use mydb
db.leads.findOne()
db.leads.find().count()
EOF
}
这个怎么样:
echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName
把它放在一个名为test.js的文件中:
db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
print(collection);
});
然后用mongo myDbName test.js运行它。
在我的情况下,我可以方便地使用\n作为分隔符的下一个mongo命令,我想要执行,然后管道他们到mongo
echo $'use your_db\ndb.yourCollection.find()' | mongo
更新版本的mongodb
echo $'use your_db\ndb.yourCollection.find()' | mongosh