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


To export MongoDB has a command mongoexport. Following is the syntax −

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

Let us create a collection with documents −

> db.demo284.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4abc9e9127fafea82a2cfc")
}
> db.demo284.insertOne({"FirstName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4abca39127fafea82a2cfd")
}
> db.demo284.insertOne({"FirstName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4abca79127fafea82a2cfe")
}

Display all documents from a collection with the help of find() method −

> db.demo284.find();

This will produce the following output −

{ "_id" : ObjectId("5e4abc9e9127fafea82a2cfc"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e4abca39127fafea82a2cfd"), "FirstName" : "Robert" }
{ "_id" : ObjectId("5e4abca79127fafea82a2cfe"), "FirstName" : "Bob" }

Following is the query to export specified field of a collection in mongodb / mongodump to file. We are exporting to the following location “C:\Users\Amit\Desktop\Result;” as shown below −

C:\Program Files\MongoDB\Server\4.0\bin>mongoexport -d test -c demo284 -f FirstName --type=csv -o C:\Users\Amit\Desktop\Result;

This will produce the following output −

2020-02-17T21:49:36.708+0530    connected to: localhost
2020-02-17T21:49:36.712+0530    exported 3 records

Following is the file location for “Result”, whose location is on the Desktop −

The contents are as follows −

Updated on: 31-Mar-2020

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements