Search code examples
javamongodbmongodb-javamorphia

Filter Embedded Array in Morphia


I have those classes:

@Entity
public class Event implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private ObjectId id;

...

@Embedded
private List<Edition> editions;

...
}

and

public class Edition implements Serializable {

private static final long serialVersionUID = 1L;

private int number;

...
}

I am trying search an Event and filter by an specific edition number.

For instance, if I have an collection such:

{
  id : <ObjectID>,
  editions : [
    {number : 1},
    {number : 2}
  ]
}

And search by edition 1 the result that I am expecting is:

{
  id : <ObjectID>,
  editions : [
    {number : 1}
  ]
}

I read about filter in morphia and my query is like this:

Query<Event> query = this.basicDAO.createQuery();
query = query.filter("editions.number", <edition number>);

return this.basicDAO.find(query).asList();

However I still get the two editions elements. What am I doing wrong?


Solution

  • By default you'll always get the full document. You can ignore specific fields (whitelisting and blacklisting supported) with .retrievedFields(false, "foo").

    You might be able to use the projection operator to retrieve the value you are looking for. Try something like this:

    query.filter("editions.number", <edition number>).retrievedFields(true, "editions.$");