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

mongo << EOF


Updated Script

#! /bin/bash

out=$(mongo --eval 'db.currentOp({op:"query"})')


./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://
Implicit session: session { "id" : UUID("ce96f3ee-f5e1-49b5-aeef-b5766328dda3") }
MongoDB server version: 3.6.8
{ "inprog" : [ ], "ok" : 1 }: No such file or directory
  • simply out=$( echo "db.currentOp()" | mongo ) ? – Wernfried Domscheit Mar 15 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 Mar 15 at 17:24
  • Can you show your full script/command – Wernfried Domscheit Mar 15 at 18:32
  • @WernfriedDomscheit Added updated script and output to the question – DB guy Mar 16 at 4:54

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
  • you should must add always some text so that ithers can use it or adapt it, you just triggert the low qualtity review – nbk Mar 15 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 Mar 16 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 Mar 16 at 5:16
  • @JJussi thatnks it worked – DB guy Mar 16 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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