Export specified field of a collection in mongodb / mongodump to file?

To export specified fields from a MongoDB collection, use the mongoexport command with the -f parameter to specify which fields to export. This utility allows you to export data in various formats including CSV and JSON.

Syntax

mongoexport -d yourDatabaseName -c yourCollectionName -f yourFieldName --type=csv -o yourFileLocation/FileName

Sample Data

Let us create a collection with sample documents ?

db.demo284.insertMany([
    {"FirstName": "Chris"},
    {"FirstName": "Robert"},
    {"FirstName": "Bob"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e4abc9e9127fafea82a2cfc"),
        ObjectId("5e4abca39127fafea82a2cfd"),
        ObjectId("5e4abca79127fafea82a2cfe")
    ]
}

Verify Sample Data

Display all documents from the collection ?

db.demo284.find();
{ "_id": ObjectId("5e4abc9e9127fafea82a2cfc"), "FirstName": "Chris" }
{ "_id": ObjectId("5e4abca39127fafea82a2cfd"), "FirstName": "Robert" }
{ "_id": ObjectId("5e4abca79127fafea82a2cfe"), "FirstName": "Bob" }

Export Specified Field

Export only the FirstName field to a CSV file ?

mongoexport -d test -c demo284 -f FirstName --type=csv -o C:\Users\Desktop\Result.csv
2020-02-17T21:49:36.708+0530    connected to: localhost
2020-02-17T21:49:36.712+0530    exported 3 records

Output File Contents

The exported CSV file will contain ?

FirstName
Chris
Robert
Bob

Key Points

  • Use -f parameter to specify field names (comma-separated for multiple fields)
  • --type=csv exports data in CSV format; use --type=json for JSON format
  • -d specifies database name, -c specifies collection name
  • The _id field is excluded when using --type=csv unless explicitly specified

Conclusion

The mongoexport command provides an efficient way to export specific fields from MongoDB collections. Use the -f parameter to control which fields are included in the exported file.

Updated on: 2026-03-15T02:17:45+05:30

578 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements