Spring Data Mongo: fetch only a specific element of a list

Viewed 21

This question has been asked a few times but not exactly how I intend it (or years have passed and I hope things have changed).

Using Spring Data Mongo's MongoRepository is it possible to fetch from the DB only a given nested element that matches some criteria?

For example, let's suppose I have the following Customer document:

public class Customer {

  @Id
  private String id;

  private String name;
  private String surname;
  private List<CreditCard> creditCards;
}

Is there a way to say "fetch ONLY the CreditCard with number XXXX?"

At the moment in my code, I find myself having to do this sort of "filtering" in memory because the query returns all the elements of the list, not only the one that matches my criteria.

I have found several posts mentioning that to cover this necessity is required to declare CreditCard as a Document itself and use @DBRef but I've read on Mongo's documentation that it may reduce significantly query performance. Also, the CreditCards are indeed assigned to a user so I do want them to be nested within that object (because then using Mongo Compass it is way easier to understand which CreditCards belong to which Customer)

1 Answers
Criteria c = Criteria.where("creditCards").elemMatch(Criteria.where("number").is("XXXX"));
mongoTemplate.find(new Query(criteria), Customer.class)

The find will fetch all the customers that has some CreditCard with number = XXXX.

Not sure if it's okay as you wrote ONLY

The CreditCard has no @Document

Related