Exporting a Collection to JSON
In this first step, you will learn the fundamental process of exporting a MongoDB collection to a JSON file. JSON (JavaScript Object Notation) is a standard format that preserves the rich, nested structure of MongoDB documents, making it ideal for backups and migrations.
First, you need to connect to the MongoDB server and create some sample data. Open the MongoDB Shell by running the following command in your terminal:
mongosh
Once you are inside the MongoDB Shell, you will see a new prompt. Now, create and switch to a new database named exportlab, and insert three documents into a users collection.
use exportlab
db.users.insertMany([
{ name: "Alice", age: 28, email: "alice@example.com", status: "active" },
{ name: "Bob", age: 35, email: "bob@example.com", status: "active" },
{ name: "Charlie", age: 42, email: "charlie@example.com", status: "inactive" }
]);
After the documents are inserted, you will see a confirmation message. Now, exit the MongoDB Shell to return to your regular terminal.
exit;
With the data in place, you can now use the mongoexport utility to export the users collection. This command specifies the database, the collection, and the output file.
mongoexport --db=exportlab --collection=users --out=$HOME/project/users.json
--db: Specifies the database to connect to (exportlab).
--collection: Specifies the collection to export (users).
--out: Specifies the path and filename for the output file ($HOME/project/users.json).
To confirm the export was successful, view the contents of the newly created JSON file.
cat ~/project/users.json
You will see the three documents you inserted, each on a new line in JSON format. This format is called JSONL (JSON Lines), where each line contains a separate, complete JSON object. Note that MongoDB adds a unique _id field to each document.
{"_id":{"$oid":"656f1a6b..."},"name":"Alice","age":28,"email":"alice@example.com","status":"active"}
{"_id":{"$oid":"656f1a6b..."},"name":"Bob","age":35,"email":"bob@example.com","status":"active"}
{"_id":{"$oid":"656f1a6b..."},"name":"Charlie","age":42,"email":"charlie@example.com","status":"inactive"}