![](/img/trans.png)
[英]Spring Boot Data and MongoDB - Filter Subdocument Array Query
[英]Spring data mongodb query for subdocument field
我正在使用 Spring Data 的 CrudRepository 和 mongodb,我在编写查询时遇到了一些问题,该查询将选择具有特定子文档值的文档。 下面是一个例子:
{
"_id" :,
"_class" :,
"matchHeader" : {
"suspend" : {},
"active" : true,
"booked" : true,
"eventId" : NumberLong(1009314492),
"status" : ""
},
"matchInfo" : {
}
}
}
我需要在matchHeader子文档中选择具有特定eventId字段的文档。 我试图写一个像findByMatchHeaderEventId(id)这样的函数,但它根本没有帮助。我怎样才能做到这一点?
The Spring Data MongoDB Reference Documentation解释了嵌套属性的属性遍历。
您需要正确定义域对象类(省略构造函数/getter/setter):
public class MyDocument {
@Id
private String id;
private MatchHeader matchHeader;
private MatchInfo matchInfo;
...
}
public class MatchHeader {
private Map<,> suspend;
private boolean active;
private boolean booked;
private Long eventId;
private String status;
}
和你的存储库类
public interface MyDocumentController extends MongoRepository<MyDocument, String> {
public List<MyDocument> findByMatchHeaderEventId(Long id);
}
否则,您可以尝试使用另一个答案中建议的findByMatchHeader_EventId 。
尝试
findByMatchHeader_EventId
代替
findByMatchHeaderEventId
您可以使用 org.springframework.data.mongodb.core.query.Query 来准备自定义查询以获取具有特定子文档 Key 值的文档。
在您的情况下,您可以编写如下代码:
Query query = new Query();
query.addCriteria(Criteria.where("matchHeader.eventId").is(id));
注意:但是对于 Query,您将需要使用 MongoTemplate。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.