MongoDB find() output to file

Viewed 11508

Is there a way to write the output of a MongoDB find() query to a file just by simply using a Linux shell command or running a script?

Right now I have to manually type in step-by-step. Example:

$ mongo
> use owndb
> db.CollectionName.find(<query>) ### and then copy and paste the result on a text editor
2 Answers

You may try this:

mongo --quiet dbname  --eval 'printjson(db.collection.find().toArray())' > output.json

You can use mongoexport for that.

Example:

mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json
Related