Definitions and Builders

The driver has introduced a number of types related to the specification of filters, updates, projections, sorts, and index keys. These types are used throughout the API.

Most of the definitions also have builders to aid in their creation. Each builder has a generic type parameter TDocument which represents the type of document with which you are working. It will almost always match the generic TDocument parameter used in an IMongoCollection<TDocument>.

Note

Projections

There are two forms of a projection definition: one where the type of the projection is known, ProjectionDefinition<TDocument, TProjection>, and one where the type of the projection is not yet known, ProjectionDefinition<TDocument>. The latter, while implicitly convertible to the first, is merely used as a building block. The high-level APIs that take a projection will always take the former. This is because, when determining how to handle a projection client-side, it is not enough to know what fields and transformations will take place. It also requires that we know how to interpret the projected shape as a .NET type. Since the driver allows you to work with custom classes, it is imperative that any projection also include the “interpretation instructions” for projecting into a custom class.

Each projection definition is implicity convertible from both a JSON string as well as a BsonDocument.

Lambda Expressions

The driver supports using expression trees to render projections. The same expression tree will sometimes render differently when used in a Find operation versus when used in an Aggregate operation. Inherently, a lambda expression contains all the information necessary to form both the projection on the server as well as the client-side result and requires no further information.

Find

When a Find projection is defined using a lambda expression, it is run client-side. The driver inspects the lambda expression to determine which fields are referenced and automatically constructs a server-side projection to return only those fields.

The following lambda expressions will all result in the projection { x: 1, y: 1, _id: 0 }. This is because we inspect the expression tree to discover all the fields that are used and tell the server to include them. We then run the lambda expression client-side. As such, Find projections support virtually the entire breadth of the C# language.

Aggregate

When an aggregate projection is defined using a lambda expression, a majority of the aggregation expression operators are supported and translated. Unlike a project for Find, no part of the lambda expression is run client-side. This means that all expressions in a projection for the Aggregation Framework must be expressible on the server.