Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read schema-less documents using Java from MongoDB

MongoDB gives the ability to write documents of any structure i.e. any number and types of key/value pairs can be written. Assuming that I use this features that my documents are indeed schema-less then how do I manage reads, basically how does the application code ( I'm using Java ) manage reads from the database.

like image 393
hershey92 Avatar asked Jun 11 '26 03:06

hershey92


1 Answers

The java driver reads and writes documents as BasicBSONObjects, which implement and are used as Map<String, Object>. Your application code is then responsible for reading this map and casting the values to the appropriate types.

A mapping framework like Morphia or Spring MongoDB can help you to convert BSONObject to your classes and vice versa.

When you want to do this yourself, you could use a Factory method which takes a BasicBSONObject, checks which keys and values it has, uses this information to create an object of the appropriate class and returns it.

like image 50
Philipp Avatar answered Jun 13 '26 17:06

Philipp



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!