how to export a csv file from the mongodb .

1,020 views
Skip to first unread message

Navneet Mathpal

unread,
Feb 13, 2014, 7:09:19 AM2/13/14
to mongod...@googlegroups.com
Hi,

I am using the follwing code but getting a csv file from the database.






package test;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
 
public class GRIDFSSample {
 
 
    public static void main(String[] args) throws IOException {
 
       
        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("newdb");
    DBCollection collection = db.getCollection("table");
 
        GridFS gridfs = new GridFS(db);
        GridFSInputFile gfsFile = gridfs.createFile(file);
        gfsFile.setFilename("books2");
        gfsFile.save();
       
        System.out.println("file saved");
 

       
    DBCursor cursor = collection.find();
       
    BasicDBObject query = new BasicDBObject("name", "books");

    cursor = collection.find(query);

        try {
           while(cursor.hasNext()) {
               System.out.println(cursor.next());
           }
        } finally {
           cursor.close();
        }
       
       
       
       
        GridFSDBFile out = gridfs.findOne(new BasicDBObject( "_id" , gfsFile.getId()) );
         
            FileOutputStream outputImage = new FileOutputStream("D:/books.csv");
              out.writeTo( outputImage);
            outputImage.close();
            }   
       
       
       
       
       
}

Jeremy Mikola

unread,
Feb 13, 2014, 5:42:59 PM2/13/14
to mongod...@googlegroups.com


On Thursday, February 13, 2014 7:09:19 AM UTC-5, Navneet Mathpal wrote:
Hi,

I am using the follwing code but getting a csv file from the database.

Can you clarify what your question is?

Also, your example code seems to create a GridFS file from an undefined "file" variable. Have you compiled and executed this code? In the future, it may be more helpful to use a separate service to share code, such as pastebin.com, rather than embed it unformatted within your post body.
Reply all
Reply to author
Forward
0 new messages