is there an explain query for mongodb linq

is there an explain query for mongodb linq  using -'c#,linq,mongodb,query-optimization,mongodb-csharp'

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


asked Sep 21, 2015 by vijayshukla80
0 votes

3 Answers

0 votes

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

var qLinq = Query.Where(x =>"jim");

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

var exp = Collection.FindAs(qLinq).Explain()

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).GetMongoQuery();

        // 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();

answered Sep 21, 2015 by abhimca2006
0 votes

Yes, there is. It shows everything .explain does and has a boolean for verbosity (it includes the time it took to execute):

var database = new MongoClient().GetServer().GetDatabase("db");
var collection = database.GetCollection("Hamsters");

var explanation = collection.AsQueryable().Where(hamster => hamster.Name == "bar").Explain(true);

It doesn't show the query though. Here's an extension method for that:

public static string GetMongoQuery(this IQueryable query)
    var mongoQuery = query as MongoQueryable;
    return mongoQuery == null ? null : mongoQuery.GetMongoQuery().ToString();


var query = collection.AsQueryable().Where(hamster => hamster.Name == "bar").GetMongoQuery();
answered Sep 21, 2015 by pradip.bhoge
0 votes

If you want this functionality in a library, I just created a GitHub project entitled

MongoDB query helper for .NET

It will:

  • Explain a LINQ query as a strongly typed object (does it use an index for example)
  • Convert a LINQ query to the JavaScript code run in MongoDB

Check it out and contribute if you find it interesting.

answered Sep 21, 2015 by deepak