Skip to content
← All posts
· Delta1 Labs MongoDBNebula

Obfuscating MongoDB POCOs without breaking BSON

The MongoDB C# driver maps each public member of your POCO to a BSON element name by reflection, and that element name is written into every document in the collection. Rename those members with an obfuscator and new writes use the renamed elements while old documents no longer deserialize — yet an in-process round-trip test still passes. Here is exactly how BsonClassMap binds a member to an element, why the polymorphic discriminator ("_t") is the second, sharper trap, and the precise Nebula keep-list that pins the fragile names while renaming the rest.

The MongoDB C# driver feels schemaless, but it is not nameless. Every document the driver writes is a BSON map whose keys come from your POCO, and the driver decides those keys by reflecting over your type at startup. Store a Device and the driver walks its public members, maps each to a BSON element, and — unless you say otherwise — uses the member name as the element name. The collection fills with documents that literally contain the strings "DeviceId" and "Status". Those strings are now part of your data, not just your code.

That is the collision. An obfuscator renames metadata identifiers; Device.DeviceId is a metadata identifier. Rename it to a and the next InsertOne writes { "a": ... }, while the ten million documents already in the collection still say { "DeviceId": ... } — and when you read one of those back, the driver looks for an element named a, cannot find it, and leaves the member at its default. No exception. The query runs, the object materializes, and DeviceId is null. This post is the precise inventory of what the driver reads by name, the second and sharper trap hiding in polymorphic collections, and the exact Nebula.NET configuration that keeps it all working.

How BsonClassMap binds a member to an element

The driver’s serialization layer is built around BsonClassMap<T>. The first time a type T is serialized or deserialized, the driver calls BsonClassMap.LookupClassMap(typeof(T)), which — if you have not registered a map by hand — runs automapping. Automapping reflects over T, and for each eligible public member it creates a BsonMemberMap whose element name defaults to the member’s own name. Consider the ordinary POCO:

public sealed class Device
{
    [BsonId] public ObjectId Id { get; set; }
    public string DeviceId { get; set; }
    public DeviceStatus Status { get; set; }
    public DateTime LastSeen { get; set; }
}

With no attributes guiding it, automapping produces the element names _id, DeviceId, Status, LastSeen. Serializing one instance yields this document:

{ "_id": ObjectId("..."), "DeviceId": "rk-0199", "Status": 1, "LastSeen": ISODate("...") }

The element names in that document are the output of member.Name at automap time. Three facts follow, and all three drive the keep-list:

  1. The element name is the member name, by default. The driver did not invent DeviceId; it copied it off the property. Rename the property and the element name the driver writes changes with it.
  2. Deserialization matches by element name, and a miss is silent. Reading a document, the driver walks the BSON elements and, for each one, looks up the member whose element name equals the key. An element with no matching member is handed to the type’s extra-elements handling — dropped by default. A member with no matching element is simply left at its default. There is no strict mode in the default path, so a rename-induced miss is indistinguishable from a field that was legitimately absent.
  3. Queries use the same map, so they stay self-consistent. When you write Builders<Device>.Filter.Eq(d => d.Status, DeviceStatus.Online), the driver renders the lambda to an element name through the same class map. So within one build, writes, reads and filters all agree. The drift only shows up against documents a different build wrote.
Pinned: stored element name still matches a member"DeviceId": "rk-0199""Status": 1name matchpublic string DeviceIdpublic DeviceStatus StatusboundboundRenamed members: old document finds no matching member"DeviceId": "rk-0199""Status": 1no matchpublic string apublic DeviceStatus bleft nullleft defaultDiscriminator: "_t" holds the CLR type name"_t": "TemperatureSensor"renamed type → no mapwrong type

The discriminator is the sharper trap

Element names are the obvious hazard. The one that bites hardest is the discriminator. When a collection stores a polymorphic hierarchy — a base Sensor with TemperatureSensor and PressureSensor subclasses — the driver writes a special _t element so it knows which concrete type to reconstruct on read. By default the discriminator value is the CLR type name:

[BsonKnownTypes(typeof(TemperatureSensor), typeof(PressureSensor))]
public abstract class Sensor { public ObjectId Id { get; set; } }

public sealed class TemperatureSensor : Sensor { public double Celsius { get; set; } }

A stored subclass document carries "_t": "TemperatureSensor". On read, the driver reads _t, looks up the registered discriminator, and instantiates that type. Now obfuscate: the type TemperatureSensor is renamed to c. New writes emit "_t": "c"; old documents still say "_t": "TemperatureSensor", and the new build’s discriminator registry — keyed on the renamed type name — has no entry for "TemperatureSensor". Deserialization throws a real BsonSerializationException here, or, worse, resolves to the wrong subtype. Unlike the quiet element miss, this one can take down an entire polymorphic read path. Type renaming is Nebula’s highest-value transform, so this is precisely the case you must handle deliberately rather than by accident.

How to pin it with Nebula

There are two durable approaches, and they combine well.

Annotate the wire contract. The robust fix decouples the stored names from the CLR names entirely:

[BsonDiscriminator("device")]
public sealed class Device
{
    [BsonId] public ObjectId Id { get; set; }
    [BsonElement("deviceId")] public string DeviceId { get; set; }
    [BsonElement("status")]   public DeviceStatus Status { get; set; }
}

An explicit [BsonElement("deviceId")] stores the string deviceId in the attribute blob, where it is data, not an identifier — so Nebula can rename DeviceId to a and the element name on the wire is still deviceId. The same holds for [BsonDiscriminator("device")]: the discriminator becomes a fixed string independent of the type name, so the type renames freely. This is also better schema hygiene, and it is worth doing before you obfuscate regardless.

Or keep the names surgically. If annotating the whole model is impractical, pin it in nebula.config.json:

{
  "rename": {
    "keep": [
      { "type": "MyApp.Domain.Documents.*", "members": "public" },
      { "typeName": "MyApp.Domain.Documents.*" }
    ]
  }
}

The first rule preserves the public member names of your document types so default element names stay stable; the second preserves the type names of the hierarchy so the default discriminators keep resolving. Everything else — DeviceRepository, your IMongoCollection wrappers, filter-building helpers, the rest of the assembly — carries no runtime name dependency and should be renamed and protected normally. Nebula’s string encryption is safe here too: the _id, SQL-free filters and any literal element names you pass by hand are decrypted transparently at runtime, so the bytes the driver sees are unchanged.

Caveats and when it breaks

The failure is bimodal, and knowing which half you are in matters. Plain element renames fail silently — null members, zeroed values, no log line — so they surface as data-quality bugs weeks later. Discriminator renames fail loudly on the first polymorphic read, which is actually the kinder outcome because your tests catch it. Watch three edges. First, [BsonIgnoreExtraElements] makes the silent half more silent by suppressing even the diagnostic you might otherwise get for an unmapped element. Second, convention packs registered via ConventionRegistry can rewrite element names (e.g. a camelCase convention) before the rename ever matters — if you rely on one, pin the member names, not a guessed casing. Third, a round-trip unit test is structurally unable to catch this: it writes and reads within one build, which is exactly the boundary the rename does not cross. Test against a document written by the previous version, or assert the raw BSON keys.

Takeaway

MongoDB’s flexibility hides a hard dependency: the element names and the type discriminators the driver writes are copied from your CLR member and type names, and they live permanently in your documents. An obfuscator that renames those identifiers changes what new writes produce while old documents keep the original keys, so reads drift and polymorphic loads throw. Decouple the contract with [BsonElement] and [BsonDiscriminator], or pin the document types’ members and names in a Nebula keep-list, and the rest of your data layer obfuscates freely — the protection lands on your repositories and query logic, exactly where your IP lives, without touching the names your database depends on.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.