BsonElement on arbitrary attribute Id?

I want to map an attribute from MongoDb to Id in the POCO class. Note that it is not the real _id in MongoDb, I wanted to use the name Id over something else.

The Mongo Object looks like

    {
       "_id": "string",
       "OtherField": "string",
       .... 
    }

The Class looks like

    class MyClass
       [BsonElement("OtherField")] 
       public string Id { get; set;}

However, even though I used the [BsonElement] decorator, the Id still reflects the _id in the MongoDb. Is it not possible to do that?

Environment:
dotnet core 3.1
MongoDb.Driver 2.10.4

Hi @sssppp and welcome in the MongoDB community :muscle:,

I’m not a C# dev but I found 2 possible solutions in the doc which could solve your issue.

  1. https://mongodb.github.io/mongo-csharp-driver/2.10/reference/bson/mapping/#the-id-member

Looks like you can use the decorator [BsonId]. If it’s set explicitly on another field, maybe it won’t be mapped to your “id” field anymore.

  1. Make a ClassMap: https://mongodb.github.io/mongo-csharp-driver/2.10/reference/bson/mapping/#creating-a-class-map

This will give you a chance to set your own serializer I guess.

@sssppp Try the suggestions from @MaBeuLux88 and let us know how it goes.