I’m having student (String) and instructor (List of String).I want to fetch the record based on the instructor count in Descending order. instructor as below
Sample: [a,b,c] -3, [e,f] -2, [g,h,i,j] -4.
I want in the order of 4 and 3 and then 2.
That is based on the field instructor array’s size.How to query this using mongoTemplate or custom mongodb query or aggregation??
Advertisement
Answer
I have found a way to sort by array size from mongodb.
Aggregation for the above is:
newAggregation(addFields().addField(“nInstructors”)
.withValue(new Document (“$size, “nInstructors”)).build(),
sort(DESC, “nInstructors”),
limit(limitCount)
);