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