MongoDB.Driver – class-based server side projection

1. Introduction

When working with NoSQL databases, your documents might be quite heavy and in some cases, you would like to get only a slice of original data. For instance, let’s assume we have an Account document which among other things contains a list of transactions

As there might be hundreds of transaction in the account object, you might want to occasionally work on a subset of original data, say for instance AccountSlim object to improve the performance

2.Exploring existing options

MongoDB.Driver has a couple of ways of defining projections so as you can operate on a slimmer object instead of a default one. For instance

Unfortunately, those are a client-side projection. This means that the entire object is returned from the database and we just serialized it to a different class. You can check it on your own by examining request and result commands sent to Mongo

In both cases requested query doesn’t contain “projection” section, so entire document is returned

Of course, there is a possibility to manually create a server-side projection, for instance

or with a strongly typed version

However, in my opinion, this is error-prone and it would be better to generate server-side projection automatically based on properties in a slim object. As I didn’t find anything like that in the official driver, here is my approach for handling this

3. Class-based server-side projection

In order to create a custom projection, all we have to do is to extend ProjectionDefinition<TSource, TResult> class and provide a RenderedProjectionDefinition with all properties which are in both “heavy” and “slim” object

As you can see we use MongoDB.Driver build-in projections to render our custom projection consisting of necessary properties. Note, that as we are using StringFieldDefinition instead of defining Bson document manually, the projection will take into account potential class mappings or attribute mappings applied to your object

Having the projection ready we can make it a bit easier to use by introducing some extensions. The first one looks as follows

which allows you to use this projection similarly like others – so by accessing Builders class

The second method will extend IFindFluent<TDocument, TProjection> interface

and thanks to it we will end up with an even better syntax

One way or another we will end up with proper projection definition which will result in a smaller document returned from the database

Source code for this post can be found here

MongoDB.Driver – class-based server side projection

Leave a Reply

Your email address will not be published. Required fields are marked *