Search code examples
c#linqmongodbquery-optimizationmongodb-.net-driver

Is there an "Explain Query" for MongoDB Linq?


Is there a way to run .explain() or equivalent on Linq queries? I would want to know

  • The text of the actual JSON query
  • The output of .explain() (indexes used, etc)
  • It would also be nice to have the execution time of the query

Solution

  • You can get the Json easily enough if you have a query wrapper;

    var qLinq = Query<T>.Where(x => x.name=="jim");
    Console.WriteLine(qLinq.ToJson());
    

    There's also an Explain() method on MongoCursor, so you could do this;

    var exp = Collection.FindAs<T>(qLinq).Explain()
    Console.WriteLine(exp.ToJson());
    

    So if you want the time taken, "millis" is in there;

    var msTaken = exp.First(x => x.Name == "millis").Value.AsInt32;
    

    If you have an IQueryable, try something like this;

    void Do(MongoCollection col, IQueryable iq)
    {
            // Json Mongo Query
            var imq = (iq as MongoQueryable<Blob>).GetMongoQuery();
            Console.WriteLine(imq.ToString());
    
            // you could also just do;
            // var cursor = col.FindAs(typeof(Blob), imq);
            var cursor = MongoCursor.Create(typeof(Blob), col, imq, ReadPreference.Nearest);
            var explainDoc = cursor.Explain();
    
            Console.WriteLine(explainDoc);
        }//Do()