How to only retrieve the nested document mongodb and spring boot

时间:2018-03-25 21:01:10

标签: spring-boot spring-data-mongodb

I have the following document and nested document.

class Foo {
   public String name;
   public String description;
   public LocalDateTime someDate;
}

@Document
class Bar {
   @Id
   public String id;
   public String details; 
   public List<Foo> foos;
}

My custom query looks as follows:

 Query query = new Query(
    Criteria.where("foo.name").is("Some name").and("id").is("myId")
 );
 List<Bar> resultList = operations.find(query, Bar.class);

I want to retrieve the the single Foo document that matches "Some name". And not the Bar document with the Foo list. How would I do this? Thanks

1 个答案:

答案 0 :(得分:1)

如果您的Foo课程在数据库中没有集合,并且已按照您在问题中的描述嵌入Bar。您需要创建一个自定义存储库以获取您要查找的内容。

interface BarRepository extends BarCustomRepository, MongoRepository<Bar, String> {

    }

interface BarCustomRepository {
Foo findFooByName(String fooName);
}


class BarRepositoryImpl implements BarCustomRepository {

@Autiwired
private MongoTemplate mongoTemplate;

@Override
Foo findFooByName(String fooName) {
Bar bar = mongoTemplate.findOne(new Query ( Criteria.where("foos.name").is(fooname)), Bar.class);

Foo foo = bar.getFooByName(fooName);// implement this method in your Bar class. // to Get a foo by fooName from foos list
return foo;
   }
}

我希望有所帮助。