If you ever use Morphia and Jongo in the same codebase, be warned they can interact in very confusing ways. Quick note for people who may not have any idea what I’m talking about: Morphia maps Java objects to Mongo documents and provides a really nice fluent interface for querying. Jongo is not quite as friendly but gives you all the same functionality as the Mongo shell. Most of the time we use Morphia at work, but once in a while for weird queries that Morphia doesn’t support (like regexes) we use Jongo.
Morphia has annotations that let you have short, space-saving field names in your documents and nice descriptive field names in your code. Jongo can convert its results into Java objects for you, but it uses Jackson to do that. Neither Jongo not Jackson know about Morphia’s annotations, which means if you used annotations to change the field names in your document, Jongo will try its best to build objects out of your results but they will be empty because it can’t match your document field names to your object field names. My coworker Eric figured that one out after I spent all afternoon swearing at it.
Fortunately, there’s a workaround! If you don’t want to dirty up your code with Morphia and Jackson annotations, you can get Jongo to give you back JsonNodes by using the JsonResultHandler like so:
Iterable<JsonNode> iterable = jongo.getCollection("collection") .find("{ query }").map(new JsonResultHandler());
Pulling fields out of a JsonNode isn’t as nice as having an object already filled in, but on the upside it’s a lot less hassle (and ugliness) than doubling up on annotations. If Jongo misbehaves for you in weird ways, try getting simple JsonNode results back instead of messing around with object mapping.