In this step, you'll learn how to format and customize your MongoDB data exports using additional mongoexport options. We'll explore how to control the output format, limit exported documents, and apply filters.
First, let's add some more diverse data to our collection:
mongosh
In the MongoDB shell, update our users collection:
use exportlab
db.users.drop() // Clear previous data
db.users.insertMany([
{
name: "Alice",
age: 28,
department: "Engineering",
salary: 85000,
active: true
},
{
name: "Bob",
age: 35,
department: "Marketing",
salary: 72000,
active: true
},
{
name: "Charlie",
age: 42,
department: "Engineering",
salary: 95000,
active: false
}
])
exit
Now, let's explore different export formatting techniques:
- Export with Pretty Formatting (JSON):
mongoexport --db=exportlab --collection=users --type=json --pretty --out=~/project/users_pretty.json
- Export Limited Number of Documents:
mongoexport --db=exportlab --collection=users --type=csv --fields=name,age,department --limit=2 --out=~/project/users_limited.csv
- Export with Query Filter:
mongoexport --db=exportlab --collection=users --type=json --query='{"department":"Engineering"}' --out=~/project/engineering_users.json
Let's verify the exported files:
echo "Pretty JSON Export:"
cat ~/project/users_pretty.json
echo -e "\nLimited CSV Export:"
cat ~/project/users_limited.csv
echo -e "\nEngineering Users Export:"
cat ~/project/engineering_users.json
Key mongoexport formatting options:
--pretty
: Formats JSON with indentation for readability
--limit
: Restricts the number of documents exported
--query
: Filters documents based on specific conditions
--fields
: Selects specific fields to export
Example output for Pretty JSON:
{
"_id": ObjectId("..."),
"name": "Alice",
"age": 28,
"department": "Engineering",
"salary": 85000,
"active": true
}