MongoTemplate Query to find Objects with child array size greater than
Asked Answered
C

1

6

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?

Concinnate answered 12/11, 2017 at 12:20 Comment(0)
T
7

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);
Torras answered 21/7, 2019 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.