🍃 MongoDB Tutorial
← PrevNext →
MongoDB mongoexport & mongoimport: JSON and CSV from the Command Line
Learn how to export a MongoDB collection to JSON or CSV with mongoexport, including limiting rows and picking specific fields, then load it back in with mongoimport.
mongoexport and mongoimport
While mongodump/mongorestore work with MongoDB's native .bson format, mongoexport/mongoimport work with plain JSON and CSV — formats you can open in a text editor or spreadsheet.
Exporting to JSON
mongoexport --db rahultechnology --collection employees --out emp11.json
mongoexport --db rahultechnology --collection employees --out /home/rahul/Music/emp.json
Export only a limited number of records:
mongoexport --db rahultechnology --collection employees --limit 2 --out emp11.json
Export only specific fields:
mongoexport --db rahultechnology --collection employees --fields empid,name --out emp11.json
Exporting to CSV
Add --type=csv and the export otherwise works the same way:
mongoexport --db rahultechnology --collection employees --type=csv --out emp11.csv
mongoexport --db rahultechnology --collection employees --limit 2 --type=csv --out emp11.csv
mongoexport --db rahultechnology --collection employees --type=csv --fields empid,name --out emp11.csv
Advertisement728 x 90
Importing JSON or CSV
mongoimport --db rahultechnology --collection emp1111 --type=json --file ./emp.json
mongoimport --db rahultechnology --collection emp1115 --type csv --file emp11.csv --headerline
--headerline tells mongoimport that the first row of the CSV contains column names, rather than data — without it, MongoDB would insert that header row as a document.
Common Errors & Troubleshooting
- CSV import inserting the header row as a document — always pass
--headerlinewhen the first row of your CSV is column names, not real data. mongoimportfailing on nested/array fields in CSV — CSV is inherently flat; nested objects and arrays don't translate cleanly to CSV rows. Use JSON for anything beyond simple flat documents.- Field type guessing going wrong —
mongoimport's CSV mode infers types automatically by default, which can turn something like a leading-zero ZIP code into a number, dropping the zero. Use--columnsHaveTypesto specify types explicitly when this matters.
Key Takeaways
mongoexport/mongoimportdeal in human-readable JSON/CSV, unlike the binary.bsonused bymongodump/mongorestore.--limitand--fieldslet you export a subset of rows or columns instead of the whole collection.- Always add
--headerlinewhen importing a CSV that has column names in its first row.
Advertisement320 x 100