Spring Data MongoDB查询子文档字段

mhe*_*yan 5 java mongodb nosql spring-data spring-data-mongodb

我在mongodb中使用Spring Data的CrudRepository,并且在编写查询时会遇到一些问题,该查询将选择具有特定子文档值的文档。这是一个例子:

{
"_id" :,
"_class" :,
"matchHeader" : {
    "suspend" : {},
    "active" : true,
    "booked" : true,
    "eventId" : NumberLong(1009314492),
    "status" : ""
},
"matchInfo" : {

    }
}
Run Code Online (Sandbox Code Playgroud)

}

我需要在matchHeader子文档中选择具有特定eventId字段的文档。我试图编写一个类似findByMatchHeaderEventId(id)的函数,但它完全没有帮助。我如何实现这一点?

Mar*_*rin 5

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;
}
Run Code Online (Sandbox Code Playgroud)

和你的存储库类

public interface MyDocumentController extends MongoRepository<MyDocument, String> {
  public List<MyDocument> findByMatchHeaderEventId(Long id);
}
Run Code Online (Sandbox Code Playgroud)

否则,您可以尝试使用另一个答案中建议的findByMatchHeader_EventId


Gau*_*oel 4

尝试

findByMatchHeader_EventId

代替

findByMatchHeaderEventId