3

I am currently having a text index in my data. I am performing a regex search and I want to make sure that the correct index is used. In the mongo shell I just used explain but how could I use explain in the C# driver?

Here's how I perform my query:

    public async Task<IEnumerable<GridFSFileInfo>> Find(string fileName)
    {
        var filter = Builders<GridFSFileInfo>.Filter.Regex(x => x.Filename, $"/.*{fileName}.*/i");
        var options = new FindOptions
        {
            Modifiers = new BsonDocument("$hint", "filename_text")
        };
        var result = new List<GridFSFileInfo>();

        using (var cursor = await Collection.Find(filter, options).ToCursorAsync())
        {
            while (await cursor.MoveNextAsync())
            {
                var batch = cursor.Current;
                result.AddRange(batch);
            }
        }

        return result;
    } 

Is there something like Collection.Find(filter, options).Explain() that returns a string or something? I searched on the web and found this: Is there an "Explain Query" for MongoDB Linq? However is seems there is no Explain method...

Kaloyan Manev
  • 406
  • 6
  • 20

1 Answers1

0

The modern mongo c# drivers support only one way to configure $explain. You can do it via FindOptions.Modifiers in the same was as you configured $hint above.

        var options = new FindOptions
        {
            Modifiers = new BsonDocument
            {
                { "$hint", "filename_text" },
                { "$explain", 1 }
            }
        };

        var cursor = coll.Find(filter, options).As<BsonDocument>().ToCursor();

Pay attention, since $explain completely changes the server response, you should change your output type to BsonDocument(or a type with fields that matches to what explain returns) via As (if it's already not BsonDocument)

dododo
  • 3,872
  • 1
  • 14
  • 37