How to read blob/binary data from MongoDB (want to read as binary data)

5,705 views
Skip to first unread message

Bharathiraja S

unread,
Jul 14, 2017, 12:19:56 PM7/14/17
to mongodb-user
Am not able read blob (binary) record from MongoDB, am using Java 3.4.2 driver.

    BasicDBObject whereClause = new BasicDBObject();
    List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
    obj.add(new BasicDBObject("blobcontentid", "20160601201035069394000000"));
    whereClause.put("$and", obj);

    MongoCursor<Document> cursor = contentcollection.find(whereClause).iterator();

    while (cursor.hasNext()) {
        Document object = cursor.next();
        System.out.println(object.getString("blobcontentid"));
        if (object.get("content") != null){
            byte[] content = (byte []) object.get("content");   
        } else {
            System.out.println("Content is empty");
        }           
    }
Error: java.lang.ClassCastException: org.bson.types.Binary cannot be cast to [B

Same record am reading like this in DB2. byte[] content = aResult.getBytes("CONTENT");

Thank you in advance! Bharathi

Kevin Adistambha

unread,
Jul 25, 2017, 2:34:04 AM7/25/17
to mongodb-user

Hi

I believe you posted the same question on StackOverflow.

You can use the get() method on a Document with built-in casting to achieve this. For example:

// Insert a binary data (byte array) into the database
Document document = new Document("blob", "This is a byte array blob".getBytes());
collection.insertOne(document);

// Find and print the inserted byte array as String
for (Document doc : collection.find()) {
    Binary bin = doc.get("blob", org.bson.types.Binary.class);
    System.out.println(new String(bin.getData()));
}

which will print This is a byte array blob which was inserted into the database back into the console.

The database will contain a BinData element as a result of the insert operation:

> db.collection.find()
{
  "_id": ObjectId("5976e23911e6772c5d32c42d"),
  "blob": BinData(0, "VGhpcyBpcyBhIGJ5dGUgYXJyYXkgYmxvYg==")
}

Note that this method may not work if you are inserting a large blob of binary data due to BSON 16MB document size limitation. If you need to insert more than 16MB of binary data, I suggest using GridFS instead.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages