Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoTemplate Query to find Objects with child array size greater than

I need to write a Query which can find objects in DB whose child array size is greater than something.

My Object looks like:

{
    "_id" : ObjectId("sbg8732god78"),
    "studentIds" : [ "d3782gdo", "d8o3g7" ]
    ...
}

I need to find all objects with studentIds array size greater than n. I was looking at available methods like:

Query query = new Query();
query.addCriteria(Criteria.where("studentIds").exists(true));
query.addCriteria(Criteria.where("studentIds").size().gt(0));

But size() method accepts an integer. How can this be done?

like image 345
Shubham A. Avatar asked Nov 12 '17 12:11

Shubham A.


1 Answers

Based on this answer, you can query for the existence of indices. This allows you to make the equivalent of a >= expression. Examples:

// find where studentIds.size() >= 1
mongoTemplate.find(Query.query(Criteria.where("studentIds.0").exists(true);

// find where studentIds.size() >= 50
mongoTemplate.find(Query.query(Criteria.where("studentIds.49").exists(true);
like image 63
phillipuniverse Avatar answered Oct 01 '22 00:10

phillipuniverse