Watch keynotes and sessions from, our virtual developer conference.

Autotest mongodb to verify query is using index

I am using mongodb and using the c# driver, I have made several queries for different parts of my application. For the different collections, I have created the appropriate indexes to support my queries, or so I hope.

I want to examine the behavior of my queries to verify that the queries are indeed using indexes. For this, my thought is to create auto-tests which can run explain on the queries and then verifying the used strategies.

However, I have a very hard time figuring out how to do this with the C# driver. An example of my queries is like this:

IMongoCollection<UserData> collection = ...

FilterDefinition<UserData> filter = Builders<UserData>.Filter.In(x => x.Email, emails);
ProjectionDefinition<UserData> projection = Builders<UserData>.Projection
   .Include(x => x.UserId)
   .Include(x => x.Email);

FindOptions<UserData> options = new FindOptions<UserData> { Projection = projection };
IAsyncCursor<UserData> findCursor = await collection.FindAsync(filter, options);

What I currently have working is the following:

FindOptions findOptions = new FindOptions { Modifiers = new BsonDocument("$explain", true) };
BsonDocument document = collection.Find(filter, findOptions).Project(projection).First();

However, the Modifiers field is deprecated, telling me to “Use individual properties instead.”, but I can’t seem to find any explain properties anywhere.

So what could/should I do? The reason for doing it as auto-tests, is that I want guard against changes to either the indexes or the queries, without having to manually verify it within the mongo-shell, but is it unreasonable or bad practice to verify the use of indexes using auto-tests? What alternatives are there?