The $unwind operator is used to deconstruct array fields. How deconstruction works β For each array element a new document is produced having that element in the position of the field array. This means that applying the unwind operator on a single document's array field which contains 10 elements, produces 10 different documents having one of the array elements instead of the array field. It is possible to define if a new document will produced in case a document either doesn't contain the array field or it is empty.
publicclassTraveler{ [BsonId]publicObjectId Id { get; set; }publicstring Name { get; set; }publicint Age { get; set; }publicList<string> Activities { get; set; }publicList<VisitedCountry> VisitedCountries { get; set; }}
LINQ query explanation
SelectMany on Activities creates the $unwind stage
new { } creates the $project stage
GroupBy groups documents by age field
Selectcreates another $project stage where Distinct ensures activities will not contain duplicate values per group - it does that by using $addToSet operator in the $group stage rather than a $push