1

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
4
  • simply out=$( echo "db.currentOp()" | mongo ) ? Commented Mar 15, 2021 at 17:17
  • @WernfriedDomscheit i did try this and I was able to save the output in variable but it says bye: No such file or directory in the end of the output, couldn't figure out why it was saying "No such file or directory" so I thought I was doing something wrong
    – DB guy
    Commented Mar 15, 2021 at 17:24
  • Can you show your full script/command Commented Mar 15, 2021 at 18:32
  • @WernfriedDomscheit Added updated script and output to the question
    – DB guy
    Commented Mar 16, 2021 at 4:54

1 Answer 1

4

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
4
  • you should must add always some text so that ithers can use it or adapt it, you just triggert the low qualtity review
    – nbk
    Commented Mar 15, 2021 at 20:26
  • why doesn't it work when i put out=$(mongo --quiet --eval="db.currentOp({op:"query"})") ; echo $out i get output 2021-03-16T10:37:14.575+0530 E QUERY [thread1] ReferenceError: query is not defined : @(shell eval):1:15 2021-03-16T10:37:14.575+0530 E QUERY [thread1] ReferenceError: query is not defined : @(shell eval):1:15
    – DB guy
    Commented Mar 16, 2021 at 5:08
  • @DBguy change "query" to 'query'... Because first "-character terminates string what started after eval=" OR use out=$(mongo --quiet --eval="db.currentOp({op:\"query\"})") ; echo $out
    – JJussi
    Commented Mar 16, 2021 at 5:16
  • @JJussi thatnks it worked
    – DB guy
    Commented Mar 16, 2021 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.