- Published on
How to Export Multiple or All MongoDB Collections
- Ashik Nesin
Recently, I wanted to validate something some data from my MongoDB database locally and convert them to JSON for ease of data manipulation.
So after reading a couple of docs I tried to use mongoexport
Tried running the following command
mongoexport --uri "mongodb+srv://user:firstname.lastname@example.org/db_name" --collection "accounts" --out accounts.json
And it did work as expected.
Then I tried various things like adding multiple collection names, leaving collection args, and also giving
* as a collection.
Nothing did work.
So apparently, mongoexport can only export one collection at a time 😭
How to export multiple collections then?
Well, just export them and then merge them.
It might not be a good solution for large applications but for small projects/side projects, it should get the job done pretty well.
So here is what we do at high level:
- Get all the collection names from the DB (automatically fetched)
- Loop through all the collection manually and then get all documents from it
- Then, stitch data from all collections together and store it in a JSON file.
For the sake of simplicity, I'll be using Node.js and a related MongoDB driver. You can use any tool that you're familiar with.
Happy exporting collections!