How to execute mongo commands through shell script

2019-01-03 11:19发布

I want to execute mongo commands in shell script.

I tried following way test.sh

#!/bin/sh

mongo myDbName

db.mycollection.findOne()

show collections

When I execute above script ./test.sh

Then mongo connection established but next commands not executed

How to execute other commands through sh script [test.sh] ?

Please help me

标签: shell sh mongodb
19条回答
老娘就宠你
2楼-- · 2019-01-03 12:06

Recently migrated from mongodb to Postgres. This is how I used the scripts.

mongo < scripts.js > inserts.sql

Read the scripts.js and output redirect to inserts.sql.

scripts.js looks like this

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), ";");

inserts.sql looks like this

INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');
查看更多
Explosion°爆炸
3楼-- · 2019-01-03 12:07

This works for me under Linux:

mongo < script.js
查看更多
We Are One
4楼-- · 2019-01-03 12:07

Put this in a file called test.js:

db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
  print(collection);
});

then run it with mongo myDbName test.js.

查看更多
聊天终结者
5楼-- · 2019-01-03 12:07

The shell script below also worked nicely for me... definite had to use the redirect that Antonin mentioned at first... that gave me the idea to test the here document.

function testMongoScript {
    mongo <<EOF
    use mydb
    db.leads.findOne()
    db.leads.find().count()
EOF
}
查看更多
Bombasti
6楼-- · 2019-01-03 12:07

In case you have authentication enabled:

mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-03 12:09

You can also evaluate a command using the --eval flag, if it is just a single command.

mongo --eval "printjson(db.serverStatus())"

Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:

mongo --eval 'db.test.update({"name":"foo"},{$set:{"this":"that"}});'

Otherwise you may see something like this:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY    SyntaxError: Unexpected token :
查看更多
登录 后发表回答