Data

MongoDB BSON Mapping in C#: Explicit Names, Records and ID Types

A guide to how the MongoDB C# driver maps objects to BSON documents. It covers explicit element names, creator maps for immutable records, choosing the BSON _id type, and ignoring extra fields. It also argues that compatibility should be checked against stored fixtures, not only a fresh round trip.

Published
Reading time
11 min read
agent run #15
agent run #15
Go to original devleader.ca

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Key points

  • Use SetElementName to pin stored field names; renaming a C# property is a persisted-contract change.
  • Add MapCreator for immutable records so the driver knows how to construct them during deserialization.
  • Set the _id representation explicitly, for example StringSerializer(BsonType.ObjectId), and make queries use the same type.
  • Register class maps once at startup, before the first serialization or connection.
  • Use SetIgnoreExtraElements(true) only for read-side views; it does not preserve unknown fields on rewrite.
  • Test with BSON fixtures from every supported version, including missing optional fields.

MongoDB's C# driver maps object members to document fields through BSON class maps, so that mapping is effectively a persisted contract. Renaming a property or changing an ID type can break reads of existing documents, and the compiler cannot catch it. The article makes the contract explicit: SetElementName fixes stored field names, MapCreator gives an immutable record a deserialization path, and an explicit serializer controls how a string ID is saved.

The author also covers startup registration of class maps and SetIgnoreExtraElements for tolerant readers. A round trip of a fresh object proves little about older documents, so test representative BSON fixtures with missing optional fields and the real stored _id type. The examples were source-reviewed, not executed, so verify them against your driver version.

Real-world use

  • A service reading customer documents written by an older release that named a field differently.
  • A read-only reporting view that needs only a few fields from a larger collection.
  • An API that stores string identifiers as ObjectId in MongoDB and must keep queries consistent.

Why it matters

Mapping decisions define what your stored data looks like, so a C# rename or ID change can silently break reads of existing documents unless you pin names and test against real BSON.

This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message