我想在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执行其他命令?
当前回答
最近从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');
其他回答
最近从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');
关于这一点也有一个官方文档页面。
该页面的例子包括:
mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
在我的设置中,我必须使用:
mongo --host="the.server.ip:port" databaseName theScript.js
mongodb的更新版本
mongosh --host="the.server.ip:port" databaseName theScript.js
当使用复制集时,必须在PRIMARY上进行写操作,所以我通常使用这样的语法,以避免弄清楚哪个主机是主主机:
mongo -host myReplicaset/anyKnownReplica
如果您已启用身份验证:
mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
更新版本
mongosh -u username -p password --authenticationDatabase auth_db_name < your_script.js