简体   繁体   中英

Query filtering data in mongo db

I have a mongo db collection data set like this.

{
    "referenceId" : NumberLong(123),   
    "title" : "Title 1",
    "couseCallNo" : "[SCPI, BICO , HSJI]"
}

And in my java code I need to retrieve this whole object using the given couseCallNo . For example if I have 'SCPI' as the coursecallNo I need to get the exact above object. Please help me out.

What I have done so far is

    QueryFilter filter = new QueryFilter();
    filter.addCriteria(Constants.Card.COURSE_CALL_NO,FilterOperator.EQUALS, courseCallNo);
    List<Course>  courseList =testRepository.find(filter);

    if(courseList != null && courseList.size()>0){
                    course =courseList.get(0);        

testRepository is

MongodbEntityRepository<Course> testRepository; 

You need to use the FilterOperator.ELEMENT_MATCH to search elements of a subarray, as stated on MongoDB documentation:

The $elemMatch operator matches documents in a collection that contain an array field with at least one element that matches all the specified query criteria.

source: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/

Your code should look like this:

 QueryFilter filter = new QueryFilter();
 filter.addCriteria(Constants.Card.COURSE_CALL_NO, FilterOperator.ELEMENT_MATCH, courseCallNo);
 List<Course>  courseList =testRepository.find(filter);

 if(courseList != null && courseList.size()>0){
     course =courseList.get(0); 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM