3

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.

3
  • Do you want to know how to connect to mongodb using a java client? getting-started-with-java-driver Commented Aug 6, 2013 at 7:19
  • definitely not. I am trying to reads documents, that have a different structure and instead of hard coding the different structure dependent reads. I am looking for some better efficient way. Commented Aug 6, 2013 at 8:14
  • 1
    Not all NoSQL databases are schemaless and/or document-oriented. I edited your question and replaced "NoSQL" with "MongoDB", because that seems to be what you mean. Commented Aug 6, 2013 at 8:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

that's right, but my real problem is in dealing with 6-8 models( if using an ODM like morhpia ). Because in the general case as each document is different they will have to map to the correct model( .class). My doubt is then how to make the decision at runtime ? Should it be a switch/if-else-if construct which is mostly not the best way to code or is there a smart alternative
The real challenge I face is in the application code, how should I modular it for better code
can you edit your question and give an example of how the documents will vary?
@hershey92 I would like to second Joe Minichino's request. When you need more specific advise, please give us a more specific example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.