Java MongoTemplate在查询中排除子关系

Java MongoTemplate在查询中排除子关系,java,mongodb,spring-data-mongodb,mongotemplate,Java,Mongodb,Spring Data Mongodb,Mongotemplate,背景: 我正在使用Spring boot和MongoDB public class User { @DBRef private List<Contact> contacts; ... public class Contact { @DBRef private List<Booking> bookings; ... public Contact(){} public Contact(Booking booking){

背景:

我正在使用Spring boot和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();
}
问题:

我想要的结果是:

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

如何从FindAllContactsForser中的查询中排除预订关系?

您只需排除
联系人字段。您的查询中的预订

@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();
}
@覆盖
公共列表findAllContactsForUser(字符串id){
Query Query=new Query().addCriteria(Criteria.where(“_id”).is(id));
query.fields().exclude(“contacts.bookings”);
User=mongoTemplate.findOne(查询,User.class);
返回user.getContacts();
}

顺便说一句,不需要
.include(contacts)
,默认情况下会包含字段。

这只会给我一个空数组=[]。我用您的模型进行了测试,它适合我。你能为你的联系人类发布完整的代码吗?你的代码中有没有为预订做“new ArrayList()”的地方?刚刚用Contact.classI的som代码更新了我的问题我在你联系人的构造函数中看到了新的ArrayList。我看不到有证据表明它被传唤了,但我怀疑是的。你能为用户添加代码吗(setContacts,getContacts+constructors)+联系人的setBookings,getBookings
@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();
}