2

A long time ago using an older version of the Mongo C# driver, it was possible to do something along the lines of this (I forget exactly).

collection.FindOne(query).Explain()

And this would provide details of query execution, indexes used, etc. using cursor.explain(). Now we're using 2.4 and would like to use explain for one of our queries.

The only question I found relating to this was this one but the driver used seems to be different again.

How do I run an explain query with the 2.4 C# driver?

Stefan
  • 17,448
  • 11
  • 60
  • 79
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

1 Answers1

3

According to an issue on MongoDB's JIRA page, it was removed from the API as an out of the box feature.

Explain is/has undergone some changes and adding it to the driver before that is done would have been a mistake. In addition, we feel that most explanations happen in the shell and not in the drivers. As a result, we've not included explain as part of the API.

Fortunately, it's still possible by supplying the query modifier in FindOptions:

var options = new FindOptions
{
    Modifiers = new BsonDocument("$explain", true)
};
var explain = await collection.Find(x => true, options)
    .Project(new BsonDocument())
    .FirstOrDefault()
    ?.ToJson();

Simply replace x => true with the query you would like to profile. I've added .ToJson() in order to get a nice human-readable JSON string.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • If I simply add Modifiers in FindOptions, it works. But since my indexes are case insensitive and are using collation, I am using this ----- query = collection.Find(filter, options: new FindOptions { Collation = request.SearchCollation, Modifiers = new BsonDocument("$explain", true) }).SortByDescending(x => x._Id).Limit(request.Limit); var explain = query.Project(new BsonDocument()).FirstOrDefault()?.ToJson(); It is giving an exception that OP_QUERY does not support collations. – shanti Jun 27 '19 at 09:54
  • @shanti Are you saying that Collation on its own works, and Modifiers on its own works, but together they produce an error? – ProgrammingLlama Jun 27 '19 at 23:52
  • yeah, this is what happened with me. – shanti Jun 28 '19 at 12:50
  • @shanti Hmm. I'm not sure, I'm afraid. You might have to post a new question about it. – ProgrammingLlama Jul 01 '19 at 00:28
  • It loos like that in the latest version of the driver FindOptions.Modifiers is not marked as obsolete. – Tim Feb 06 '20 at 02:41