4

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
Zac
  • 149
  • 1
  • 2
  • 12
  • Possible duplicate of [Is there a way to 'pretty' print MongoDB shell output to a file?](https://stackoverflow.com/questions/13104800/is-there-a-way-to-pretty-print-mongodb-shell-output-to-a-file) – Neodan Nov 24 '17 at 09:59

2 Answers2

7

You may try this:

mongo --quiet dbname  --eval 'printjson(db.collection.find().toArray())' > output.json
Neodan
  • 5,154
  • 2
  • 27
  • 38
Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
  • 1
    Also it is a more like as workaround than a solution. For this task exists `mongoexport`. – Neodan Nov 24 '17 at 10:02
  • Thank for your comment @Neodan. I search find this suitable for this question however did I violate SO rules ? I will delete this answer If It doesn't commit standard rules for stack overflow member – Bùi Đức Khánh Nov 24 '17 at 14:46
  • 1
    Always is better to mark post as duplicate, than duplicate an answer (-; – Neodan Nov 24 '17 at 15:00
5

You can use mongoexport for that.

Example:

mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json
Neodan
  • 5,154
  • 2
  • 27
  • 38
  • I often think about mongoexport when I need to export whole db or a collections. However, with this answer I also find that mongoexport has option --query for query too. So It may be better than my answer – Bùi Đức Khánh Nov 24 '17 at 14:48
  • 1
    For export of whole db or collection is better to use mongodump (https://docs.mongodb.com/manual/reference/program/mongodump/) – Neodan Nov 24 '17 at 14:57
  • Yes I appreciate your comment – Bùi Đức Khánh Nov 24 '17 at 14:58
  • Perhaps I may need to modify my question because I did not specify whether I am exporting the collection or not. The example I gave suggested I am intending to export the whole collection but I do occasionally need to produce an output file based on a query. Appreciated all the discussions and explanations with thanks. – Zac Nov 27 '17 at 01:08
  • 1
    @theciezac `mongoexport` have `--query` (or `-q`) for that ;-) – Neodan Nov 27 '17 at 07:30