# Obfuscating MongoDB POCOs without breaking BSON


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](https://delta1labs.com/products/nebula) 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:

```csharp
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:

```json
{ "_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.

<figure class="my-8"><svg viewBox="0 0 700 320" role="img" aria-label="BsonClassMap maps each public member of a POCO to a BSON element name by reflection. With element names pinned, a document written by the old build still binds under the new build. After renaming, new documents use renamed keys and old documents no longer match any member, so the driver leaves them at their defaults with no exception. The type-name discriminator in the _t field breaks the same way for polymorphic collections." style="width:100%;height:auto"><defs><style>.ti{font:600 13px system-ui;fill:#3b82f6}.lbl{font:11px system-ui;fill:#64748b}.mono{font:600 11px ui-monospace,monospace;fill:#0f172a}.okbox{fill:#2dd4bf20;stroke:#2dd4bf}.docbox{fill:#3b82f620;stroke:#3b82f6}.badbox{fill:#f8717120;stroke:#f87171}.neu{fill:#64748b20;stroke:#64748b}</style><marker id="ok" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#2dd4bf"/></marker><marker id="bad" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#f87171"/></marker><text class="ti" x="16" y="22">Pinned: stored element name still matches a member</text><rect class="docbox" x="16" y="34" width="168" height="26" rx="4"/><text class="mono" x="26" y="51">"DeviceId": "rk-0199"</text><rect class="docbox" x="16" y="66" width="168" height="26" rx="4"/><text class="mono" x="26" y="83">"Status": 1</text><path d="M184 47 h104" stroke="#2dd4bf" stroke-width="2" fill="none" marker-end="url(#ok)"/><path d="M184 79 h104" stroke="#2dd4bf" stroke-width="2" fill="none" marker-end="url(#ok)"/><text class="lbl" x="200" y="42">name match</text><rect class="okbox" x="292" y="34" width="190" height="26" rx="4"/><text class="mono" x="302" y="51">public string DeviceId</text><rect class="okbox" x="292" y="66" width="190" height="26" rx="4"/><text class="mono" x="302" y="83">public DeviceStatus Status</text><text class="lbl" x="500" y="51">bound</text><text class="lbl" x="500" y="83">bound</text><text class="ti" x="16" y="150">Renamed members: old document finds no matching member</text><rect class="docbox" x="16" y="162" width="168" height="26" rx="4"/><text class="mono" x="26" y="179">"DeviceId": "rk-0199"</text><rect class="docbox" x="16" y="194" width="168" height="26" rx="4"/><text class="mono" x="26" y="211">"Status": 1</text><path d="M184 175 h104" stroke="#f87171" stroke-width="2" stroke-dasharray="5 4" fill="none" marker-end="url(#bad)"/><path d="M184 207 h104" stroke="#f87171" stroke-width="2" stroke-dasharray="5 4" fill="none" marker-end="url(#bad)"/><text class="lbl" x="206" y="170">no match</text><rect class="badbox" x="292" y="162" width="190" height="26" rx="4"/><text class="mono" x="302" y="179">public string a</text><rect class="badbox" x="292" y="194" width="190" height="26" rx="4"/><text class="mono" x="302" y="211">public DeviceStatus b</text><text class="lbl" x="500" y="179">left null</text><text class="lbl" x="500" y="211">left default</text><text class="ti" x="16" y="262">Discriminator: "_t" holds the CLR type name</text><rect class="docbox" x="16" y="274" width="210" height="24" rx="4"/><text class="mono" x="26" y="290">"_t": "TemperatureSensor"</text><path d="M226 286 h90" stroke="#f87171" stroke-width="2" stroke-dasharray="5 4" fill="none" marker-end="url(#bad)"/><rect class="badbox" x="320" y="274" width="180" height="24" rx="4"/><text class="mono" x="330" y="290">renamed type → no map</text><text class="lbl" x="516" y="290">wrong type</text></svg></figure>

## 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**:

```csharp
[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:

```csharp
[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`:

```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.

