Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mongo command results in to a flat file

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.

like image 285
QVSJ Avatar asked Oct 10 '12 16:10

QVSJ


People also ask

Is MongoDB a flat file?

MongoDB stores data in flat files using their own binary storage objects. This means that data storage is very compact and efficient, perfect for high data volumes. MongoDB stores data in JSON-like documents, which makes the database very flexible and scalable. MongoDB is a document-oriented database model.

How do I export data from MongoDB to CSV?

Export MongoDB to CSV (e.g. Excel) Open the Export Wizard and select your export source. This screen only appears if you haven't chosen an item in the Connection Tree, run a previous query, or selected specific documents. Next, choose CSV as the export format then click Next.


1 Answers

you can try the following from the command line

mongo 127.0.0.1/db --eval "var c = db.collection.find(); while(c.hasNext()) {printjson(c.next())}" >> test.txt 

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

mongo 127.0.0.1/db script.js >> test.txt 

I hope this helps

like image 83
peshkira Avatar answered Sep 20 '22 22:09

peshkira