Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-fparameter to specify field names (comma-separated for multiple fields) -
--type=csvexports data in CSV format; use--type=jsonfor JSON format -
-dspecifies database name,-cspecifies collection name - The
_idfield is excluded when using--type=csvunless 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.
Advertisements
