Specifically, I want to print the results of a mongodb find()
to a file. The JSON object is too large so I\'m unable to view the entire object with the shell wi
Put your query (e.g. db.someCollection.find().pretty()
) to a javascript file, let's say query.js
. Then run it in your operating system's shell using command:
mongo yourDb < query.js > outputFile
Query result will be in the file named 'outputFile'.
By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.
DBQuery.shellBatchSize = 100
.
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!
Using this answer from Asya Kamsky, I wrote a one-line bat script for Windows. The line looks like this:
mongo --quiet %1 --eval "printjson(db.%2.find().toArray())" > output.json
Then one can run it:
exportToJson.bat DbName CollectionName
Also there is mongoexport for that, but I'm not sure since which version it is available.
Example:
mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json