Search code examples
javamongodbmorphia

Morphia to return List of strings which are the fields of all documents


If I got a collection full of following elements

@Entity
public void MyEntity{
  public String name;
  public String type;
  ...
}

And I want to return a List<String> (or Set) of not the elements, but only their name fields.

List<String> allNames = datasotre.find(MyEntity.class).asList("name");

This is sample query, there is no such method of Morphia datastore.


Solution

  • To limit the fields returned call the "retrievedFields" method on Query. For example, to only get the name field of all MyEntity objects:

    datastore.find(MyEntity.class).retrievedFields( true, "name").asList()
    

    Edit - You can get a list Strings using the following query as long as you don't mind that the list will only contain unique values (i.e. no duplicate names):

    DBCollection m = datastore.getCollection( MyEntity.class );
    List names = m.distinct( "name", new BasicDBObject() );
    

    The "names" list will only contain Strings.