MongoDB C# driver class mapping: map MongoDB nested fields to flat class - Stack Overflow

admin2025-04-17  3

I’m trying to do a very simple thing, I want to map a MongoDB document with nested fields to a flat class like so:

Document:

{ 
    code: "123",
    data: {
        other_code: "456",
    }
}

Class:

public class MyClass 
{
    [BsonElement("code")]
    public string Code { get; set; }
    
    [BsonElement("data.other_code")] // <= syntax not supported for Deserialization
    public string OtherCode { get; set; }
}

And then I want to be able to use it in a typed query like this:

var filter = Builders<MyClass>.Filter.Where(x => x.OtherCode == "456")

The filter generated does uses my string with dot notation:

"data.other_code" : "456"

But when I execute the query with:

List<Myclass> results = collection.Find(filter).ToList();

The member OtherCode is not populated and stays NULL.

I know I can do something like this:

public class MyClass
{
    [BsonElement("code")]
    public string Code { get; set; }

    [BsonElement("data")]
    public Data Data { get; set; }

    [BsonIgnore]
    public string OtherCode => Data?.OtherCode

}

public class Data
{
    [BsonElement("other_code")]
    public string OtherCode{ get; set; }
}

But I would like not to have to create a class everytime I need to map a nested field.

I tried to write a custom BsonSerializer but the Deserialize method is never called.

Any thoughts on how I could do it ?

Thanks for your help !

转载请注明原文地址:http://anycun.com/QandA/1744867414a88744.html