Search code examples
javaspringmongodbspring-bootmongorepository

How to filter in mongo repository for array of objects


Here i'm using MongoRepository and i need to query a list of objects that includes certain id in an array of objects inside.

The document structure :

{
 "_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")
}

The Repository :

@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);

}

User model class:

@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;

So im trying to retrieve User objects that includes a bookletSignups object with the passing bookletId value. But the result is empty. What has gone wrong here?


Solution

  • I would say you need to modify your query to looks like this:

    @Repository
    public interface UserRepository extends MongoRepository<User,String> {
    
       @org.springframework.data.mongodb.repository.Query(value = "{ 'bookletSignups': { $elemMatch: { 'bookletId' : ?0 } }}")
       List<User> findByBookletId(String id);
    
    }
    

    If you check MongoDB documentation for $elemMatch, link to documentation, you can see that basically in $elemMatch operator you are using field in embedded object, so you don't need to specify again name of array in which you are searching for objects.