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

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

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

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


当前回答

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

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

来自编写脚本的shell文档:

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

其他回答

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

#!/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

最近从mongodb迁移到Postgres。这是我使用脚本的方式。

mongo < scripts.js > inserts.sql

读取scripts.js,输出重定向到inserts.sql。

js看起来像这样

use myDb;
var string = "INSERT INTO table(a, b) VALUES";
db.getCollection('collectionName').find({}).forEach(function (object) {
    string += "('" + String(object.description) + "','" + object.name + "'),";
});
print(string.substring(0, string.length - 1), ";");

插入。SQL看起来像这样

INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');

单shell脚本解决方案,能够传递mongo参数(——quiet, dbname,等):

#!/usr/bin/env -S mongo --quiet localhost:27017/test

cur = db.myCollection.find({});
while(cur.hasNext()) {
  printjson(cur.next());
}

-S标志可能不适用于所有平台。

这个怎么样:

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