Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FilterDefinition serialization does not work as expected in new MongoDb driver

Tags:

mongodb

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?

like image 943
YMC Avatar asked Sep 16 '25 02:09

YMC


1 Answers

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);
like image 120
Kevin Smith Avatar answered Sep 17 '25 19:09

Kevin Smith