How do I export the results of a MongoDB command to a flat file
For example, If I am to get db.collectionname.find()
into a flat file.
I tried db.collectionname.find() >> "test.txt"
doesnt seem to work.
How do I export the results of a MongoDB command to a flat file
For example, If I am to get db.collectionname.find()
into a flat file.
I tried db.collectionname.find() >> "test.txt"
doesnt seem to work.
I know of no way to do that from the mongo shell directly, but you can get mongoexport to execute queries and send the results to a file with the -q and -o options:
The above hits queries the profiles collection in the models database grabbing the JSON document for _id = "MRD641000". Works for me.
Try this - returns a json file with the data of the query, you can change
.json
for.txt
and other.mongoexport --db db_name --collection collection_name --csv --out file_name.csv -f field1,field2, field3
Having missed the db needing to be the actual db in Peshkira's answer, here is a general syntax for a one liner in shell (assuming no password):
I tested it both on my mac and Google cloud Ubuntu 15 with Mongo 3+.
you can try the following from the command line
assuming you have a database called 'db' running on localhost and a collection called 'collection' this will export all records into a file called test.txt
If you have a longer script that you want to execute you can also create a script.js file and just use
I hope this helps