Home > Blockchain >  Use [DB] for Mongodb with shell
Use [DB] for Mongodb with shell

Time:04-02

I am researching now the simple "use" command for the mongo command. Please help me.

I just want save the my query in a file, but before that i need to connect to a certain database. For that i tried to find a "use" command like in sql, but could not find anything.

I just want to execute something like

mongo ....--use [db] --eval 'db.find' > save.query

CodePudding user response:

In your question, you didn't specify what platform you're using, are you using Linux? Windows? Anyway, if you want to use the command line for mongo db then I would recommend to use the mongodb shell. Download the mongodb shell https://www.mongodb.com/try/download/shell and select what platform you're using.

CodePudding user response:

https://www.mongodb.com/docs/mongodb-shell/run-commands/#mongosh-usage

That sais you have use <database> command

CodePudding user response:

I just got it. You can just add the database name:

mongo [dbname] --host etc. 

and it worked.

CodePudding user response:

This is the easiest way in linux:

Option 1 ( command line params )

 echo "db.exampleollection.find({}).forEach(function(d){printjson(d)})" | mongo --quiet exampledatabase --host "examplehost" --port "examplePort" --authenticationDatabase=admin -u "exampleuser" -p "examplepassword"  > output.json

Explained:

Send the command you need to execute via echo to the mongo shell and redirect the output to the result file. Add the option --quiet to suppress the shell printed info You can provide the database directly in as comman line argument.

Option 2 : same way but URI format:

 echo "show collections" | mongo "mongodb://user:pass@host:port/database?authSource=admin"  --quiet
  • Related