Home > Back-end >  I want to sort the Mongodb data based on Array size
I want to sort the Mongodb data based on Array size

Time:01-09

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??

CodePudding user response:

Query1

  • add a new field with the $size of the instructor array
  • sort descending by that field
  • unset that field

*sort doesn't accept an expression we couldn't do it in 1 stage without adding a new field.

Test code here

aggregate(
[{"$set":{"nInstructors":{"$size":"$instructor"}}},
 {"$sort":{"nInstructors":-1}},
 {"$unset":["nInstructors"]}])

Query2

  • same as above but checks if array first, to avoid errors if field has other type or missing.

Test code here

aggregate(
[{"$set":
  {"nInstructors":
   {"$cond":
    [{"$isArray":["$instructor"]}, {"$size":"$instructor"}, 0]}}},
 {"$sort":{"nInstructors":-1}},
 {"$unset":["nInstructors"]}])

CodePudding user response:

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) );

  •  Tags:  
  • Related