我想在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运行它。

其他回答

如果您已启用身份验证:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js

更新版本

mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js

这个怎么样:

echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName

遗留的mongo shell已从MongoDB中移除,并将于2022年发布第6版

有一种使用新shell mongosh执行shell脚本的新方法

来自编写脚本的shell文档:

您可以使用mongosh从命令行执行脚本,而无需进入mongosh控制台 要指定文件名,请使用——file或-f参数指定文件名 您可能还需要指定连接信息

将mongo脚本放到.js文件中。

然后执行mongo < yourFile.js

Ex:

Demo.js //file有你的脚本

use sample  //db name
show collections

将此文件保存在“c:\db-scripts”中

然后在cmd提示符中转到"c:\db-scripts"

C:\db-scripts>mongo < demo.js

这将在mongo中执行代码并显示输出

C:\db-scripts>mongo < demo.js
Mongo shell version: 3.0.4
Connecting to: test
switched to db sample
users   //collection name
tasks   //collection name
bye
C:\db-scripts>

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

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

cat file.sh | mongo <EXPECTED_COLLECTION>