Aggregation: Return just objects which contains maximum 5 elements cumulated in different arrays

Hi everybody.

I have a classRoom Object, which stores under desks fields multiple desk objects. This desk object, part of desks array mentioned above, has the the following structure:

desk[0] = 
{ value: {
   .... other fields,
   students: Array of `student` object
   }
}

I want to mention that students: array {_id: string (not ObjectId), name: string}
I want to achieve the following:
Return just those classRooms that has a total of students that is LESS than 5.

Do you have any suggestions for that ?
Thank you very much !

Hi @Teodor_Aspataritei and welcome to the MongoDB community forum!!

It would be helpful in understanding and replicating in local environment, if you could share the following information

  1. A sample document from the collection
  2. The desired output example for the aggregation query.
  3. The aggregation query you have tried.
  4. The MongoDB version you are using.

Best Regards
Aasawari

1 Like

Guys here is the solution that I created and it works !

Sharing in case anyone else needs it.

  {
    '$unwind': {
      'path': '$desks'
    }
  }, {
    '$match': {
      'desks.value.students': {
        '$type': 'array'
      }
    }
  }, {
    '$addFields': {
      'totalStudents': {
        '$sum': {
          '$size': '$desks.value.students'
        }
      }
    }
  }, {
    '$match': {
      'totalStudents': {
        '$lt': 5
      }
    }
  }
1 Like