Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb query for subdocument field

I'm using Spring Data's CrudRepository with mongodb and i have some issue to write a query which will select a document with specific subdocument value. Here's an example:

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

    }
}

}

i need to select the document with specific eventId field in matchHeader subdocument. i tried to write a function like this findByMatchHeaderEventId(id) but it doesn't helped at all.how can i achieve that?

like image 514
mherBaghinyan Avatar asked Nov 12 '14 12:11

mherBaghinyan


Video Answer


2 Answers

Property traversal for nested properties is explained in The Spring Data MongoDB Reference Documentation.

You need to properly define your domain object class (constructor/getters/setters omitted):

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

and your repository class

public interface MyDocumentController extends MongoRepository<MyDocument, String> {
  public List<MyDocument> findByMatchHeaderEventId(Long id);
}

Otherwise you can try the findByMatchHeader_EventId suggested in another answer.

like image 123
Marc Tarin Avatar answered Oct 28 '22 13:10

Marc Tarin


Try

findByMatchHeader_EventId

instead of

findByMatchHeaderEventId

like image 44
Gaurav Goel Avatar answered Oct 28 '22 14:10

Gaurav Goel