Is there a way to run .explain()
or equivalent on Linq queries? I would want to know
.explain()
(indexes used, etc)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()
If you want this functionality in a library, I just created a GitHub project entitled
MongoDB query helper for .NET
https://github.com/mikeckennedy/mongodb-query-helper-for-dotnet
It will:
Check it out and contribute if you find it interesting.
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<Hamster>("Hamsters");
var explanation = collection.AsQueryable().Where(hamster => hamster.Name == "bar").Explain(true);
Console.WriteLine(explanation);
It doesn't show the query though. Here's an extension method for that:
public static string GetMongoQuery<TItem>(this IQueryable<TItem> query)
{
var mongoQuery = query as MongoQueryable<TItem>;
return mongoQuery == null ? null : mongoQuery.GetMongoQuery().ToString();
}
Usage:
var query = collection.AsQueryable().Where(hamster => hamster.Name == "bar").GetMongoQuery();
Console.WriteLine(query);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With