0xRLA
0xRLA

Reputation: 3369

Java MongoTemplate exclude child relations in query

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?

Upvotes: 0

Views: 2871

Answers (1)

alexbt
alexbt

Reputation: 17025

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.

Upvotes: 1

Related Questions