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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With