Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
like image 518
Shy Peleg Avatar asked Aug 17 '15 10:08

Shy Peleg


3 Answers

I was trying to solve the same problem today. Here is what I found.

public static class MongoExtensions
{
    public static BsonDocument RenderToBsonDocument<T>(this FilterDefinition<T> filter)
    {
        var serializerRegistry = BsonSerializer.SerializerRegistry;
        var documentSerializer = serializerRegistry.GetSerializer<T>();
        return filter.Render(documentSerializer, serializerRegistry);
    }
}

I didn't have access to a collection when I was calling it, so I couldn't use the above solutions.

This allows you to do

var json = filter.RenderToBsonDocument().ToJson();
like image 169
zrbecker Avatar answered Nov 03 '22 15:11

zrbecker


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 } })
like image 26
i3arnon Avatar answered Nov 03 '22 14:11

i3arnon


You are able to perform that using the collection's properties:

var result = filter.Render(collection.DocumentSerializer,
                           collection.Settings.SerializerRegistry).ToString();
like image 21
Vladyslav Furdak Avatar answered Nov 03 '22 16:11

Vladyslav Furdak