Array operators
Overview
There are many times when you want to match documents based on array field values. Luckily, MongoDB and the C# driver provide the following 3 array query operators that help you build array based queries.
Operator
Description
Size
Match documents based on the array's size
ElemMatch
Match documents when array's elements match specified conditions
All
Match documents when all specified values are contained in the array
Other than the operators themselves, you can create array field base queries using lambda expressions and the methods provided by
Enumerable, such asEnumerable.Any

Size operator - $size
The $size operator is applied on array fields and matches documents when an array has a specific number of elements. MongoDB C# driver, doesn't contain a dedicated method for the $size operator but can resolve it from the Countproperty or Count() method of IEnumerabletypes.
The following sample finds:
Travelerdocuments having VisitedCountries array with exact 5 elementsTravelerdocuments having VisitedCountries array with more than 10 elements
ElemMatch operator - $elemMatch
The $elemMatch operator is used to match elements inside array fields based on one or more criteria.
The sample filters Traveler documents that their VisitedCountries array field contains a VisitedCountry element with name Greece and TimesVisited = 3.
You might be temped to match array elements using the $and operator as follow:
This is wrong because it doesn't apply the criteria on each array element at a time but at all elements. This means that it might match documents that indeed contain a visited country with name "Greece" which hasn't TimesVisited = 3, but a document matched because it also contains another visited country, e.g. Italy with TimesVisited = 3.
The following sample filters Traveler documents that their VisitedCountries array field contains a VisitedCountry element TimesVisited = 3 but this time, the country's name can be either Greece or Italy.
Enumerable.Any - AnyEq
To check if an array field contains a specified value you can use the Enumerable.Any or the FilterDefinitionBuilder<T>.AnyEq methods.
The sample finds the Traveler documents where "Greece" is contained in the VisitedCountries array field.
You can go further, and add an || operator in the Any method. This will combine $elemMatch and $in operators to build the query.
All operator - $all
The $all operator is applied on array fields and matches documents when the array field contains all the items specified. You use the All operator when you want to ensure that an array contains (or doesn't) a list of values.
The sample finds all Traveler documents having "Backpacking" and "Climbing" values on their Activities list. Activities is an array of string values.
Last updated