rez
rez

Reputation: 2087

mongodb eval returns zero on failure, how to check if it failed?

I'm sending some commands to mongodb using --eval option as below:

mongo --quiet --eval 'printjson("use admin"); printjson(db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } ))'

I was trying to check $? in my code to check whether the command failed. But it returns 0 even on mongodb errors. How can I check if it failed?

Upvotes: 0

Views: 468

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59523

What is the purpose of the printjson?

You don't have to switch to admin database for db.adminCommand, and printjson("use admin") has no effect anyway.

I would do it like this:

ret=$( mongo --quiet --eval='db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } ).ok' )
echo $ret
1


ret=$( mongo --quiet --eval='db.adminCommand( { typo_setFeatureCompatibilityVersion: "4.4" } ).ok' )
echo $ret
0

Or use

ret=$( mongo --quiet --eval='db.adminCommand( { typo_setFeatureCompatibilityVersion: "4.4" } ).errmsg' )
if [[ -z "$ret" ]] ; then
   echo "Success"
else
   echo "Error message: $ret"
fi

You get return code =! 0 if the mongo fails, the mongo commands have no effect on the return code. Example:

mongo "mongodb://admin:WRONG_PASSWORD@localhost" --quiet --eval='db.adminCommand( { setFeatureCompatibilityVersion: "4.4" } ).errmsg'

Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:374:17
@(connect):3:6
exception: connect failed
exiting with code 1

echo $?
1

Upvotes: 1

Related Questions