How to view the MongoDB Query when using the C# LINQ Provider

If you’re using the Official MongoDB C# Driver from 10gen, you may want to occasionally verify that the generated query matches your LINQ query (or at least that it’s building something efficient).

Take for example this query:

var query = 
    (from r in DataLayer.Database.GetCollection<Research>().AsQueryable<Research>()
        where !r.Deleted
        select new
        {
            Id = r.Id,
            Title = r.Title,
            Created = r.Created
        }).Skip(PageSize * page).Take(PageSize);

query.DebugWriteMongoQueryText();

I wanted to verify that the query was checking the Deleted property, and see if the projection was considered as part of the query, so a few lines of code later …

public static string ToMongoQueryText<TQueryable>(this IQueryable<TQueryable> query)
{
    return (query as MongoQueryable<TQueryable>).GetMongoQuery().ToString();            
}

[Conditional("DEBUG")]
public static void DebugWriteMongoQueryText<TQuerable>(this IQueryable<TQuerable> query)
{
    Debug.WriteLine("QUERY: " + query.ToMongoQueryText());
}

I added two extension methods to IQueryable. As the return type for the query in my sample is actually an anonymous type, it wasn’t something I could easily type in the Immediate Window in Visual Studio for example.

<>f__AnonymousType2<string,string,System.DateTime>

No thanks  <>f__AnonymousType2<string,string,System.DateTime>.

I added the Conditional Attribute so that the code would only execute in a Debug build of my application.

query.DebugWriteMongoQueryText();

The output of the query above was:

QUERY: { "Deleted" : { "$ne" : true } }

As you’ll see, the anonymous projection wasn’t considered. Unfortunately, that’s a known issue with the current driver. This mattered in my above example, as some of the fields could contain a large amount of data that wasn’t needed by the current display.