在这里,我正在使用MongoRepository,我需要查询一个对象列表,其中包括内部对象数组中的某些ID。
文档结构:
{
"_id" : ObjectId("5ccc1c54a3d5eed9a6b8015a"),
"email" : "sineth3@gmail.com",
"name" : "edward3",
"businessName" : "aroma3",
"phone" : "07177222233",
"address" : "no 100 NY",
"bookletSignups" : [
{
"bookletId" : "sample-booklet",
"contactName" : "john doe"
},
{
"bookletId" : "sample-booklet1",
"contactName" : "john doe1"
}
],
"eventSignups" : [
{
"eventId" : "sample-event",
"contactName" : "john doe2"
},
{
"eventId" : "sample-event 1",
"contactName" : "john doe3"
}
],
"infoSignups" : [
{
"infoRequestId" : "sample-info ",
"contactName" : "john doe4"
},
{
"infoRequestId" : "sample-event 1",
"contactName" : "john doe5"
}
],
"webinarSignups" : [
{
"webinarId" : "sample-webinar ",
"contactName" : "john doe6"
},
{
"webinarId" : "sample-webinar 1",
"contactName" : "john doe7"
}
],
"updatedTime" : ISODate("2016-03-03T08:00:00Z")
}
存储库:
@Repository
public interface UserRepository extends MongoRepository<User,String> {
@org.springframework.data.mongodb.repository.Query(value = "{ 'bookletSignups': { $elemMatch: { 'bookletSignups.bookletId' : ?0 } }}")
List<User> findByBookletId(String id);
}
用户模型类:
@Id
private String id;
private String email;
private String name;
private String businessName;
private String phone;
private String address;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date updatedTime;
@Field("bookletSignups")
@DBRef
private List<BookletSignUp> bookletSignups;
@Field("eventSignups")
@DBRef
private List<EventSignUp> eventSignups;
@Field("infoSignups")
@DBRef
private List<InfoSignUp> infoSignups;
@Field("webinarSignups")
@DBRef
private List<WebinarSignUp> webinarSignups;
因此,我试图检索包含带有传递的bookletId值的bookletSignups对象的User对象。但是结果是空的。这里出了什么问题?
答案 0 :(得分:1)
我会说您需要将查询修改为如下形式:
@Repository
public interface UserRepository extends MongoRepository<User,String> {
@org.springframework.data.mongodb.repository.Query(value = "{ 'bookletSignups': { $elemMatch: { 'bookletId' : ?0 } }}")
List<User> findByBookletId(String id);
}
如果查看MongoDB文档中的$elemMatch
,link to documentation,您会发现基本上在$elemMatch
运算符中,您正在使用嵌入对象中的字段,因此您无需再次指定您要在其中搜索对象的数组的名称。