Search code examples
javamongodbmorphia

Query that returns only certain fields?


I've got a very large, structured document(s) stored in MongoDB, and am using Morphia to query and model it in Java. I'd like to write a query that only returns a handful of the fields in that document, rather than returning the entire thing. I've looked in the documentation on the Morphia site, but couldn't find anything that explains how to do this. Is it possible to write a query like this with Morphia? In pseudocode it would be something like

GET doc.propertyA, doc.propertyB, doc.propertyX FROM doc WHERE doc.someOtherProperty = 'Foo'

Thoughts? Or is Morphia not designed to operate in this manner? Is there something better I could try?


Solution

  • Take a look at this: https://rawgithub.com/wiki/mongodb/morphia/javadoc/0.103/apidocs/com/google/code/morphia/query/Query.html#retrievedFields%28boolean,%20java.lang.String...%29

    You'll still get back your entity objects but they'll only contain the fields listed.