How to prevent id serialization to_id by mongodb c# driver for nested objects?

mongo
mongo
170 Points
8 Posts

I'm using mongodb c# diver in .net core application and having nested object with id field. I don't want to id serialized to _id in db documents. Instead of keep id in  the db json.

public class MainClass
{
  public string Id { get; set; }
  public string Name { get; set; }
  public NestedClass NestedClass { get; set; }
}
public class NestedClass
{
  public string Id { get; set; }
  public string Value { get; set; }
  public string Description { get; set; }
}

In Db serialized as:

{
    "_id": "89547bf9-e282-46f8-82e1-d29b3c07068e",
    "name": "abc",
    "nestedClass": {
        "_id": "Some Text",
        "Value": "value",
        "Description": null
    }
}

I need output some thing like:

{
    "_id": "89547bf9-e282-46f8-82e1-d29b3c07068e",
    "name": "abc",
    "nestedClass": {
        "id": "Some Text",
        "Value": "value",
        "Description": null
    }
}
Views: 936
Total Answered: 1
Total Marked As Answer: 1
Posted On: 15-Feb-2023 06:00

Share:   fb twitter linkedin
Answers
Smith
Smith
2890 Points
78 Posts
         

It's default behavior to convert id to _id of mongodb driver. We can prevent it by decorating following attribute in child or nested object:

  • [BsonNoId] - specifies that the class's IdMember should be null
  • [BsonElement("id")] - we can specify the name of the element

 

Add following attributes in the nested class:

[BsonNoId]
public class NestedClass
{
    [BsonElement("id")]
    public string Id { get; set; }
    public string Value { get; set; }
    public string Description { get; set; }
}
Posted On: 15-Feb-2023 22:42
Thanks. It works.
 - mongo  24-Apr-2023 05:44
 Log In to Chat