mongodb

FilterDefinition serialization does not work as expected in new MongoDb driver


With mongodb .net driver versions earlier than 2 we built Query<Person> object (part of its api) and were able to serialize it into a mongodb query with ToJson() method. With mongodb driver v.2.5 now we have new FilterDefinition<Person> to build similar queries, but serialization does not work properly anymore:

FilterDefinition<Person> filter = Builders<Person>.Filter.Eq(t => t.Name, "Alex");
filter.ToBsonDocument() // returns {{ "_t" : "SimpleFilterDefinition`2" }}
filter.ToJson() // returns same {{ "_t" : "SimpleFilterDefinition`2" }}
filter.ToString() // returns MongoDB.Driver.SimpleFilterDefinition`2[TestApp.Person,System.String]

Same happens to other type of filtering operations and other entities. Any suggestions on how to make serialization work right?


Solution

  • Try the following

    var personSerializer = new MongoClient()
        .GetDatabase("test")
        .Settings
        .SerializerRegistry
        .GetSerializer<Person>();
    
    var filter = Builders<Person>.Filter.Eq(x => x.FirstName, "Bob");
    
    var doc = filter.Render(personSerializer, BsonSerializer.SerializerRegistry);
    
    Console.WriteLine(doc);