1

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"

DimiDak
  • 4,820
  • 2
  • 26
  • 32

3 Answers3

4

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"
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
  • Thanx, the `show databases` was an example of how I want to be executing commands from the terminal without being inside the mongo shell. – DimiDak Mar 11 '22 at 09:56
1

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 ...

R2D2
  • 9,410
  • 2
  • 12
  • 28
  • This has a lot of irrelevant info but it gave me the general idea which is `echo "" | mongo` . Thanx – DimiDak Mar 10 '22 at 16:04
0

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
DimiDak
  • 4,820
  • 2
  • 26
  • 32
  • Hello DimiDak can we use same for setting parameters like this echo "db.adminCommand({setFeatureCompatibilityVersion: "4.4"})" | mongo dbname – Samurai Sep 27 '22 at 08:56