How to Export MongoDB Collection to JSON File
To export a MongoDB collection to a JSON file, use the
mongoexport command-line tool with the --collection and --out options. For example, mongoexport --db yourDB --collection yourCollection --out output.json exports the collection data into a JSON file named output.json.Syntax
The basic syntax for exporting a MongoDB collection to a JSON file is:
mongoexport: The command-line tool to export data.--db: Specifies the database name.--collection: Specifies the collection name to export.--out: Defines the output file path and name.--jsonArray(optional): Exports data as a JSON array instead of one JSON document per line.
bash
mongoexport --db <database_name> --collection <collection_name> --out <file_name>.json [--jsonArray]
Example
This example exports the users collection from the mydatabase database into a file named users.json. It uses the --jsonArray option to export the data as a JSON array.
bash
mongoexport --db mydatabase --collection users --out users.json --jsonArray
Output
[
{"_id": {"$oid": "60c72b2f9af1f2d9c8e4b8a1"}, "name": "Alice", "age": 30},
{"_id": {"$oid": "60c72b3a9af1f2d9c8e4b8a2"}, "name": "Bob", "age": 25}
]
Common Pitfalls
Common mistakes when exporting collections include:
- Not specifying the correct database or collection name, resulting in no data exported.
- Forgetting to use
--jsonArrayif you want a valid JSON array file; otherwise, the output is one JSON document per line. - Running
mongoexportwithout having it installed or not in your system's PATH. - Not having proper permissions to read the database or write the output file.
bash
Wrong (missing --jsonArray): mongoexport --db mydatabase --collection users --out users.json Right (with --jsonArray): mongoexport --db mydatabase --collection users --out users.json --jsonArray
Quick Reference
| Option | Description |
|---|---|
| --db | Specify the database to export from |
| --collection | Specify the collection to export |
| --out | Output file path and name |
| --jsonArray | Export data as a JSON array (optional) |
| --query ' | Export documents matching a filter (optional) |
Key Takeaways
Use the mongoexport tool with --db, --collection, and --out options to export collections.
Add --jsonArray to export data as a valid JSON array file.
Ensure correct database and collection names to avoid empty exports.
Check permissions and mongoexport installation before running the command.
You can filter exported data using the --query option if needed.