Save output of a Mongo Command to a Variable bash script
-
17-03-2021 - |
Question
I have been writing a script to find and kill slow mongodb queries, how can I store output of db.currentOp() in a variable?
current I am using this but failing
#! /bin/bash
out=""
mongo << EOF
out=db.currentOp();
EOF
echo"----------------------------"
echo"$out"
Updated Script
#! /bin/bash
out=$(mongo --eval 'db.currentOp({op:"query"})')
echo"-----------------------"
echo"$out"
Output
./kill_slow_mongo_queries.sh: line 4: echo-----------------------: command not found
./kill_slow_mongo_queries.sh: line 5: echoMongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("ce96f3ee-f5e1-49b5-aeef-b5766328dda3") }
MongoDB server version: 3.6.8
{ "inprog" : [ ], "ok" : 1 }: No such file or directory
Solution
Mongo -command have multiple parameters that are handy in this case.
'--eval' let you run commands and '--quiet' keep all clutter away
out=$(mongo --quiet --eval="db.currentOp()") ; echo $out
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange