MongoDB
editStore an ID
When the project references MongoDB.Bson, the generator adds a BSON serializer to each ID and registers it with [BsonSerializer]. A property of an ID type is stored as the value:
public sealed class ProjectDocument
{
public ProjectId Id { get; set; }
public string? Name { get; set; }
}var project = new ProjectDocument { Id = ProjectId.FromInt32(42), Name = "Documentation" };
var document = project.ToBsonDocument();
Assert.Equal(42, document["_id"].AsInt32);
var deserialized = BsonSerializer.Deserialize<ProjectDocument>(document);
Assert.Equal(ProjectId.FromInt32(42), deserialized.Id);An ID property named Id is the _id of the document, as for any other type.
How values are stored
- The serializer writes the value with the serializer that MongoDB uses for the underlying type. Your registrations apply: MongoDB.Bson 3 needs a representation for
Guidvalues, such asBsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard)), and IDs that wrap aGuiduse it. Int128,UInt128andBigIntegervalues are stored as strings, andHalfvalues asfloat(BSON double).- A
nullID of a class type is stored asnull.
Use ObjectId values
An ID can wrap a MongoDB.Bson.ObjectId: [StronglyTypedId<ObjectId>]. It is stored as an ObjectId, and written as a string in JSON. See Underlying types.