2

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"

3 Answers 3

5

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx, the show databases was an example of how I want to be executing commands from the terminal without being inside the mongo shell.
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 ...

1 Comment

This has a lot of irrelevant info but it gave me the general idea which is echo "<cmd>" | mongo . Thanx
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

1 Comment

Hello DimiDak can we use same for setting parameters like this echo "db.adminCommand({setFeatureCompatibilityVersion: "4.4"})" | mongo dbname

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.