2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am trying to understand how I can do the same with Mongo, while being in the shell
I can easily get the output of a query I want by being outside of the shell and executing the following command:
mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" >> sample.json
The above way is fine, but it requires me to exit the mongo shell or open a new terminal tab to execute this command. It would be very convenient if I could simply do this while still being inside the shell.
P.S: the Question is an offshoot of a question I posted on SO
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File
However, you can log all the shell session if you invoked the shell with tee command:
Then you'll get a file with this content:
To remove all the commands and keep only the json output, you can use a command similar to:
Then you'll get:
We can do it this way -
The
shellBatchSize
argument is used to determine how many rows is the mongo client allowed to print. Its default value is 20.It may be useful to you to simply increase the number of results that get displayed
and then you can select all the results out of the terminal in one go and paste into a text file.
It is what I am going to do :)
(from : https://stackoverflow.com/a/3705615/1290746)
Combining several conditions:
myScriptFile.js
Sending the query from terminal
-z
key ofsed
allows treat output as a single multi-line string$>
mongo localhost --quiet myScriptFile.js | sed -z 's/^.*CUT_TO_HERE\n//' > output.json
If you invoke the shell with script-file, db address, and --quiet arguments, you can redirect the output (made with print() for example) to a file: