Search code examples
c#.netmongodbmongodb-.net-drivermongodb-csharp-2.0

Translate FilterDefinition<TDocument> to regular json mongo query that i can run in a mongo shell


I have many complex queries that I sometimes wish to check directly against Mongo for debugging \ explaining() purposes. With the newer 2.0+ c# driver, i'm not sure how to do this. With the previous version there was a thing called IMongoQuery and This worked.

A simple example:

FilterDefinition<LalalaEvent> filter = Builders<LalalaEvent>.Filter
    .Where(e => ids.Contains(e.Id) && e.Deleted != true );

Solution

  • If you're using the latest version of the driver, which is 2.0.1 you can easily put that filter in a Find operation, get back an IFindFluent and print its ToString:

    var filter = Builders<LalalaEvent>.Filter.Where(e => ids.Contains(e.Id) && e.Deleted != true);
    var findFluent = collection.Find(filter);
    Console.WriteLine(findFluent);
    

    For example for me this prints:

    find({ "_id" : { "$in" : [1, 2, 3] }, "Deleted" : { "$ne" : true } })