skip to Main Content

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

4

Answers


  1. Chosen as BEST ANSWER

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

    mongo [dbname] --host etc. 
    

    and it worked.


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

    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search