Home > Enterprise >  How to execute mongodb commands from bash shell?
How to execute mongodb commands from bash shell?

Time:03-11

I searched and found that one can use --eval but this does not work from CLI as you were inside mongodb shell.

For example I can not show databases with --eval

mongo -u root -p pass --eval "show dbs"

MongoDB shell version v4.2.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("80746969-2c86-45dc-603f-7f98882e578c") }
MongoDB server version: 4.2.18
2022-03-10T15:33:22.711 0000 E  QUERY    [js] uncaught exception: SyntaxError: unexpected token: identifier :
@(shell eval):1:5
2022-03-10T15:33:22.711 0000 E  -        [main] exiting with code -4

I was hoping there is something like mysql's mysql -e "show databases"

CodePudding user response:

You can do as follow:

 echo 'db.testCollection.findOne({ "_id": "xxx" })' |  mongo --port 27017 testDatabase --authenticationDatabase=admin -u myUser -p  <myPassWord>  > output.txt

But there is many other ways to do it , check this ticket there is multiple options already described ...

CodePudding user response:

This seems like a valid workaround:

  echo "show dbs" | mongo -u root -p pass

Returns:

MongoDB shell version v4.2.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("") }
MongoDB server version: 4.2.18
admin              0.000GB
config             0.000GB
local              0.025GB
bye

CodePudding user response:

show databases is a special command. Instead you can use listDatabases admin command:

mongo "mongodb://root:pass@localhost:27017/?authSource=admin" --norc --quiet --eval "db.adminCommand( { listDatabases: 1 } ).databases"
  • Related