Shadowman
Shadowman

Reputation: 12049

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?

Upvotes: 0

Views: 258

Answers (2)

berus97
berus97

Reputation: 384

example is better than words.

Query returns only "_id" field.

datastore.createQuery(entityClazz.class).retrievedFields(true, Mapper.ID_KEY);

Upvotes: 0

evanchooly
evanchooly

Reputation: 6243

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.

Upvotes: 1

Related Questions