Java MongoTemplate exclude child relations in query

2.6k views Asked by At

Background:

I'm using Spring-boot and MongoDB.

public class User {
   @DBRef
   private List<Contact> contacts;
   ...


public class Contact {

   @DBRef
   private List<Booking> bookings;
   ...

   public Contact(){}

   public Contact(Booking booking){
       this.bookings = new ArrayList<Booking>();
       this.bookings.add(booking);
       ...
   }

@Override
public List<Contact> findAllContactsForUser(String id) {
    Query query = new Query().addCriteria(Criteria
            .where("_id").is(id));
    query.fields().include("contacts");
    User user = mongoTemplate.findOne(query, User.class);
    return user.getContacts();
}

Output from findAllContactsForUser:

[
   {
     "field":"value",
     "bookings": [
                   "field":"value"
                 ]
   }
]

Problem:

The result I want:

[
   {
     "field":"value",
     "bookings": null
   }
]

How do I exclude the bookings relationship from my query in findAllContactsForUser?

1

There are 1 answers

4
alexbt On

You just need to exclude the field contacts.bookings in your query:

@Override
public List<Contact> findAllContactsForUser(String id) {
    Query query = new Query().addCriteria(Criteria.where("_id").is(id));
    query.fields().exclude("contacts.bookings");
    User user = mongoTemplate.findOne(query, User.class);
    return user.getContacts();
}

By the way, no need for the .include(contacts), fields are included by default.