Search code examples
c#.netmongodb-.net-drivermongodb-indexes

MongoDB C# OfType() Indexing behavior


Suppose I have this query over a Collection:

var dbMarkers = Features.AsQueryable<DBFeature>()
                        .OfType<DBPointFeature>()
                        .Where(f => f.parentFeatureSetId = parentFeatureSetId );

And the features are indexed (sparse) by:

{ "parentFeatureSetId": 1 }

As I understand, the C# driver uses the Type information DBFeature and DBPointFeature as an additional filter when building the query.

I would like to know if the Index is applied BEFORE the type Query, so it will be limited to the Index subset.

If not, it would be first fetching all the items of a particular type (which is a set much bigger than the idexed set), and the index would be almost pointless.

What is the behavior of MongoDB in this case?

Thank you very much!!


Solution

  • If only parentFeatureSetId is indexed, then that will be the index MongoDB uses. It will first find the documents with the specified parentFeatureSetId and then scan them for the ones with the right type.

    You could however have the type discriminator field (_t) indexed as well, which may improve performance. In this case mongo will intersect both indexes and scan only the subset of items that have both the right type and parentFeatureSetId


    Important note: The C# driver will not use DBFeature while building the query, it will only use DBPointFeature which you noted the documents must be specifically. The generic AsQueryable is only there to ease the usage.