5

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Try

findByMatchHeader_EventId

instead of

findByMatchHeaderEventId

Comments

0

You can use org.springframework.data.mongodb.core.query.Query for preparing a custom query for fetching documents with specific subdocument Key value.

In your case, you can code like:

Query query = new Query();
query.addCriteria(Criteria.where("matchHeader.eventId").is(id));

Note: But for Query you will be required to use MongoTemplate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.