Search code examples
javamongodbspring-data

Reference Child List in Spring Data Mongodb Query Method WITHOUT Using @Query or Filtering Parent Initial Results


What I am asking may not be possible since all of the similar examples seem to use either @Query or do an initial find on parent fields and then stream/filter/collect on the child list.

EventChange contains a list of Subscription(s) as follows:

public class Subscription{
    private String id;
    private String subscribeDn;
    private DocumentType documentType;
    private Object document;
}

public class EventChange{
    private String id;
    private String eventDn;
    private Action action;
    private DocumentType documentType;
    private List<Subscription> subscriptions;
}

For the EventChange repository I have been tasked to return to the user (userDn) all of the subscriptions and events that they did not initiate but did subscribe. So basically I will look for events where the eventDn != userDn and the documentType == Subscription.DocumentType and where the userDn is found in at least ONE of the List<Subscription>.

This is as far as I can get with the QueryMethod technique.

public List<EventChange> findByDnAndDocumentTypeAndActionAnd??????(String userDn, DocumentType documentType, Action action, ????);

The question marks obviously are the placeholder where I think the related values would go if this is possible. I work on a closed system so the code presented is manually typed to illustrate the scenario.

Thank you in advance for your time and effort!


Solution

  • Followed a suggestion by a local dev if you reference the collection in association with the value you are looking for along with the keyword In, then mongodb is smart enough to reverse the lookup and look for the value in the child collection list.

    MongoDb version this worked with: 6.0.5

    public List<EventChange> findByDnAndDocumentTypeAndActionAndSubscriptions_SubscribeDnIn(String userDn, DocumentType documentType, Action action, String userDn)
    

    One note in the Intellij dev environment, it did not like this method naming and kept pointing it out as a warning.

    Hope this followup helps!