🎯Match

Filter documents

The match stage is used to filter documents that will be used as input to the next stage in the pipeline. The filtered documents match one or more specified conditions.

One way to use the Match stage in a pipeline is to use the Aggregate method in a IMongoCollection<T> and chain the Match method.

IMongoCollection<T>.Aggregate()
    .Match(FilterDefinition<T> filter)

The following sample builds an aggregate with only one stage included. An aggregate with only one stage which happens to be a Match stage is actually equal to a simple find result with the same filter definitions. The sample filters User documents having salary between 3500 and 5000.

Match.cs
var collection = database
    .GetCollection<User>(Constants.UsersCollection);

// creates an aggregate pipeline
var aggregate = collection.Aggregate()
    .Match(Builders<User>.Filter.Gte(u => u.Salary, 3500) &
           Builders<User>.Filter.Lte(u => u.Salary, 5000));

var highSalaryUsers = await aggregate.ToListAsync();

Match with Project

The following sample adds a Match stage to filter Traveler documents that have visited "Greece" exactly 3 times and projects the Id, Name, Age and VisitedCountries of each document. Notice that the match stage has been applied to array field elements using the $elemMatch operator.

Match.cs
var travelersCollection = travelersDatabase.
    GetCollection<Traveler>(Constants.TravelersCollection);

// match stage
var visitedGreeceExactly3Times = Builders<Traveler>.Filter
    .ElemMatch(t => t.VisitedCountries,
    country => country.Name == "Greece" && 
    country.TimesVisited == 3);

// projection stage
var simpleProjection = Builders<Traveler>.Projection
    .Include(t => t.Name)
    .Include(t => t.Age)
    .Include(t => t.VisitedCountries);

// build the pipeline
var greeceAggregate = travelersCollection
    .Aggregate()
    .Match(visitedGreeceExactly3Times) // match stage
    .Project(simpleProjection); // projection stage

var greeceVisited3Times = await greeceAggregate.ToListAsync();

Last updated