Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while reading blob (binary) data from mongodb using Java

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

like image 295
Bharathiraja S Avatar asked Apr 24 '26 12:04

Bharathiraja S


1 Answers

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.

like image 83
kevinadi Avatar answered Apr 27 '26 03:04

kevinadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!