user1312837
user1312837

Reputation: 1298

Write data to raw BSON

At this time I serialize my data to BasicDBObject. MongoDB convert it to BSON ans send it to server.

How can I manually write data to BSON to avoid secondary serializing?

http://api.mongodb.org/java/current/com/mongodb/BasicDBObject.html only extends HashMap

http://api.mongodb.org/java/current/com/mongodb/RawDBObject.html is readonly

Upvotes: 0

Views: 806

Answers (2)

Trisha
Trisha

Reputation: 3931

The only way to write directly to BSON is to write the byte buffers themselves, and send them over the network to the server. Since this is the primary job of the Java driver, you're much less likely to have bugs communicating with MongoDB if you use the driver and BasicDBObject.

Using BasicDBObject is the most optimized path in the Java driver, so if you think performance is going to be an issue for you, I suggest you come up with your performance requirements (is it throughput or latency you're interested in? What numbers are you aiming for?) and write appropriate performance tests using both the Java driver and your own serialization.

The JVM is extremely smart, and will optimise the code paths which are most regularly used in your program. You might find that HotSpot optimizes your program and the Java driver such that there is no advantage for you to write your own serialization.

Upvotes: 2

DuckMaestro
DuckMaestro

Reputation: 15905

Take a look at BasicDBObject.java. Any data you put in there is not immediately serialized to BSON, but is only gathered as references to existing Java objects. There shouldn't be duplicate work spent on BSON serialization.

If you still want to manually generate your own BSON, you are probably looking at modifying or subclassing one or more of the types here: https://github.com/mongodb/mongo-java-driver/tree/master/src/main/com/mongodb.

Upvotes: 1

Related Questions