Printing Mongo query output to a file while in the mongo shell
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:
$ mongo | tee file.txtMongoDB shell version: 2.4.2connecting to: test> printjson({this: 'is a test'}){ "this" : "is a test" }> printjson({this: 'is another test'}){ "this" : "is another test" }> exitbye
Then you'll get a file with this content:
MongoDB shell version: 2.4.2connecting to: test> printjson({this: 'is a test'}){ "this" : "is a test" }> printjson({this: 'is another test'}){ "this" : "is another test" }> exitbye
To remove all the commands and keep only the json output, you can use a command similar to:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json
Then you'll get:
{ "this" : "is a test" }{ "this" : "is another test" }
We can do it this way -
mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.json
The shellBatchSize
argument is used to determine how many rows is the mongo client allowed to print. Its default value is 20.
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:
mongo localhost/mydatabase --quiet myScriptFile.js > output