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

前端 未结 3 1280
时光说笑
时光说笑 2020-12-14 08:44

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 t

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 09:04

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

    public static class MongoExtensions
    {
        public static BsonDocument RenderToBsonDocument(this FilterDefinition filter)
        {
            var serializerRegistry = BsonSerializer.SerializerRegistry;
            var documentSerializer = serializerRegistry.GetSerializer();
            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();
    

提交回复
热议问题