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条回答
一纸荒年 Trace。
2楼-- · 2019-01-03 11:56

--shell flag can also be used for javascript files

 mongo --shell /path/to/jsfile/test.js 
查看更多
甜甜的少女心
3楼-- · 2019-01-03 11:57

Thank you printf! In a Linux environment, here's a better way to have only one file run the show. Say you have two files, mongoCmds.js with multiple commands:

use someDb
db.someColl.find()

and then the driver shell file, runMongoCmds.sh

mongo < mongoCmds.js

Instead, have just one file, runMongoCmds.sh containing

printf "use someDb\ndb.someColl.find()" | mongo

Bash's printf is much more robust than echo and allows for the \n between commands to force them on multiple lines.

查看更多
狗以群分
4楼-- · 2019-01-03 11:58

Create a script file; write commands:

#!/bin/sh
mongo < file.js

In file.js write your mongo query:

db.collection.find({"myValue":null}).count();
查看更多
叼着烟拽天下
5楼-- · 2019-01-03 12:00

If you want to handle it with one line it's an easy way.

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

cat file.sh | mongo <EXPECTED_COLLECTION>
查看更多
forever°为你锁心
6楼-- · 2019-01-03 12:01

In my case, I can conveniently use \n as separator for the next mongo command I want to execute then pipe them to mongo

echo $'use your_db\ndb.yourCollection.find()' | mongo
查看更多
你好瞎i
7楼-- · 2019-01-03 12:03
mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"
查看更多
登录 后发表回答