5

在这里,我使用的是 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 对象的用户对象。但结果是空的。这里出了什么问题?

4

1 回答 1

4

我会说您需要将查询修改为如下所示:

@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链接到文档,您可以看到基本上在$elemMatch运算符中您正在使用嵌入对象中的字段,因此您不需要再次指定要在其中搜索对象的数组的名称。

于 2019-05-03T12:03:27.873 回答