I use MongoDB in one of my Java projects. After a DB schema change, I found myself modifying existing code at a lot of places to perform the change from e.g.:
Object result = collection.findOne();
to
Object result = collection.findOne().get("ThisField").get("ThatField");
Now, things are relatively simple in the findOne() case, but they get more complex when find() and the associated cursors come to play.
In most cases, it would have been far easier if I could modify the query, rather than its result. I have already experimented with retrieving specfic fields only, but as far as I can tell, that only masks the rest of the fields – it does not change the structure of the object.
-
Is it possible to specify a query so that the objects that form the values of a specific field are “promoted” to a top-level object, thus removing the
.get("this").get("that")calls? -
As a further step, does MongoDB support any equivalent to the views, as seen in conventional databases? Something that might allow existing code to continue working in case of a schema change?
It seems that MongoDB does not currently have any server-side equivalent of the relational database views. The MongoDB Map/Reduce support is apparently suitable only for batch operations, which makes it useless for an online database with real-time updates.
As a workaround, I turned to a client-side solution. I took advantage of the fact that the Java driver is open source and thus I could easily work out how it is structured.
More specifically, I was able to extend and replace the default BSON decoder for the collections of interest and transparently relocate the fields that had moved.