Why can a MongoDB equality match on an embedded BSON document fail on field order, and what do duplicate keys do to the same assumption?
answer
- BSON elements form an ordered list
- same fields, different bytes
- dot notation matches per field
- language maps may reorder keys
- format silent, server unsupported
basics
~20 sBSON documents are ordered, and MongoDB compares embedded documents including order, so {a:1,b:2} does not equal {b:2,a:1}. Match with dot notation. Duplicate keys are not forbidden by the format, but MongoDB does not support them.
solid answer
~40 sA BSON document is an ordered list of elements, so `{a: 1, b: 2}` and `{b: 2, a: 1}` are different documents. When MongoDB compares embedded documents, field order counts, so a filter written as `{address: {zip: "0150", city: "Oslo"}}` misses a document stored with `city` first. Dot notation, `{"address.city": "Oslo", "address.zip": "0150"}`, tests each field on its own and ignores order. Order also leaks through client code, because a language's map type may not keep it. Duplicate keys break the same assumption from the other side: the BSON specification does not prohibit them, but it gives them no meaning, and MongoDB does not support such documents even if an insert appears to succeed. Default wire validation does not catch them. In 9.0, `validate` with `checkBSONConformance: true` does.
code
plaintext · 11 lines{a: 1, b: 2}
13 00 00 00 length 19
10 61 00 01 00 00 00 int32 "a" = 1 (7 bytes)
10 62 00 02 00 00 00 int32 "b" = 2 (7 bytes)
00 terminator
{b: 2, a: 1}
13 00 00 00 length 19
10 62 00 02 00 00 00 int32 "b" = 2 (7 bytes)
10 61 00 01 00 00 00 int32 "a" = 1 (7 bytes)
00 terminatorgo deeper
Recall that BSON keeps fields in order, unlike a JSON object, and that a filter on a whole embedded document must match its fields in that order. Dot notation avoids this.
Explain why equal-looking documents have different bytes, how each filter form behaves, and where order is set or changed: map types, _id going first, $rename and projection stages.
Diagnose a missed match by reading stored order, then remove the dependence. Separate who says what about duplicates: the format is silent, drivers vary, and the server does not support them.
Decide how far a data model may rely on exact embedded matches at all. A review rule favouring dot notation is cheap, compared with chasing order drift across services and languages.
## An ordered list, not a map The BSON specification defines a document as zero or more **ordered** key/value pairs. Its grammar is a length, a list of elements and a terminating NUL, with each element in the position where it was written. JSON objects are defined as unordered, and most languages decode them into maps. That difference is the source of the trouble: a programmer thinks "same fields, same document", and the format says otherwise. Two documents with the same fields in a different order have different bytes. Both are 19 bytes here: a 4-byte length, two 7-byte elements (one type byte, a 2-byte key with its NUL, a 4-byte `int32`) and the final NUL. ## How the equality match fails The manual is direct: when comparing documents, field ordering is significant, so `{a: 1, b: 1}` is not equal to `{b: 1, a: 1}`. - `{address: {city: "Oslo", zip: "0150"}}` matches a stored `address` only if it has exactly those fields in exactly that order. - `{address: {zip: "0150", city: "Oslo"}}` misses the same stored document, and returns no error. - `{"address.city": "Oslo", "address.zip": "0150"}` tests each path separately, so order is irrelevant, and extra fields in `address` are allowed too. A numeric type difference is not the same kind of problem: Int32 1 and Int64 1 compare as equal values. Order and field names are what an embedded document match is strict about. ## Where the order comes from | Layer | What happens to order | |---|---| | Driver encoding | Follows the application's structure; an unordered map gives an arbitrary order | | JavaScript objects | Integer-like keys enumerate first, whatever the written order | | Write path | Preserved, except that `_id` always goes first and `$rename` may reorder fields | | Query results | `$project`, `$addFields`, `$set` and `$unset` may reorder fields, so do not rely on it | | Extended JSON | A generator should keep the order, but JSON objects are unordered, so a JSON library may lose it | So a document's order can change between two services without anyone choosing to change it. A unit test that compares decoded maps sees the two forms as equal, so it passes while the production filter misses. Two writers that build `address` from different structures store different byte sequences, and a filter written against one misses the other. ## Places where order carries meaning Order is not only a hazard. Several MongoDB features rely on it, which is why a client needs an order-preserving structure for them: - **Sort specifications**: `{a: 1, b: -1}` sorts by `a` first. - **Compound index keys**: `{a: 1, b: 1}` and `{b: 1, a: 1}` are different indexes. - **Commands**: in an `OP_MSG` body, the command name must be the first key. ## Duplicate keys: who says what The rule has different owners, and mixing them up is the usual error. 1. **The BSON specification** does not prohibit duplicate key names and defines no meaning for them. 2. **The Extended JSON specification** is deliberately silent on the matter. 3. **Drivers vary.** The manual warns that a driver may silently drop duplicates before insertion, or may send an invalid document. On the read side, a decoder that builds a map keeps one value: PyMongo's Python decoder assigns `result[key] = value`, so the last occurrence wins. 4. **The MongoDB server** does not support such documents. Inserting one "isn't supported even if the insert succeeds, or appears to succeed", updates carry the same warning, and querying such documents gives inconsistent results. The server's default check on incoming BSON is structural and does not look for duplicates, so a duplicate can get in. ## Finding duplicates - **`validate` with `checkBSONConformance: true`** runs the full BSON check in the MongoDB 9.0 source, whose duplicate error reads `Duplicate key found`. The manual's warning names `full: true`, but in the r9.0.4 source `full` alone selects the lighter validator, so use the conformance option. - **`$objectToArray`** turns a document into an array of pairs, where a duplicate appears twice. The manual gives this as working in any version. - **Decoding into a map hides the problem**, because one value has already gone. Inspect raw BSON, or use the operator above.
- Why might a driver's map type make the problem intermittent?If a language's map does not promise an order, the encoded field order can depend on the map's implementation or its contents. Filters then match on some runs and miss on others. Using dot notation for matches, and an order-preserving structure where order has meaning, removes that dependence.
- Does the server reject a document with duplicate field names when it arrives?Not through the default validation of incoming BSON, which checks structure such as lengths, type bytes and terminators. Duplicate names are a conformance check, which in MongoDB 9.0 runs under `validate` with `checkBSONConformance: true`. The manual's position is that such documents are unsupported, even when an insert appears to succeed.
- If field order matters in stored data, does it matter when you replace a document?Yes. A replacement stores the document as you built it, except that `_id` goes first, so a client that builds fields in a new order changes the stored order. Any exact embedded match written against the old order then stops matching.
- Two BSON documents with the same fields and values are equal in any order.
- A filter on an embedded document matches regardless of how the fields are ordered.
- The BSON specification forbids duplicate keys.
- The server rejects duplicate field names when a document arrives.
- Dot notation also depends on the stored field order.
- A driver always preserves field order, whatever structure the application passes in.
Assumes MongoDB 9.0: the duplicate check runs under validate with checkBSONConformance, per the r9.0.4 source.