我想在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');
其他回答
谢谢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强制它们在多行上。
最近从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脚本放到.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>
把它放在一个名为test.js的文件中:
db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
print(collection);
});
然后用mongo myDbName test.js运行它。
这个怎么样:
echo "db.mycollection.findOne()" | mongo myDbName
echo "show collections" | mongo myDbName