{"record":{"id":"4ea40c398bec961a","repo":"mongodb/node-mongodb-native","slug":"document-is-larger-than-the-maximum-size-this-s","errorCode":null,"errorMessage":"Document is larger than the maximum size ${this.s.maxBsonObjectSize}","messagePattern":"Document is larger than the maximum size (.+?)","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/bulk/ordered.ts","lineNumber":46,"sourceCode":"    if (this.s.usingAutoEncryption) {\n      bsonSize = BSON.calculateObjectSize(document, {\n        checkKeys: false,\n        ignoreUndefined: false\n      } as any);\n    } else {\n      const bson = this.s.bsonOptions;\n      buffer = BSON.serialize(document, {\n        checkKeys: this.s.checkKeys,\n        ignoreUndefined: bson.ignoreUndefined,\n        serializeFunctions: bson.serializeFunctions\n      });\n      bsonSize = buffer.length;\n    }\n\n    // Throw error if the doc is bigger than the max BSON size\n    if (bsonSize >= this.s.maxBsonObjectSize)\n      // TODO(NODE-3483): Change this to MongoBSONError\n      throw new MongoInvalidArgumentError(\n        `Document is larger than the maximum size ${this.s.maxBsonObjectSize}`\n      );\n\n    // Create a new batch object if we don't have a current one\n    if (this.s.currentBatch == null) {\n      this.s.currentBatch = new Batch(batchType, this.s.currentIndex);\n    }\n\n    const maxKeySize = this.s.maxKeySize;\n\n    // Check if we need to create a new batch\n    if (\n      // New batch if we exceed the max batch op size\n      this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize ||\n      // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc,\n      // since we can't sent an empty batch\n      (this.s.currentBatchSize > 0 &&\n        this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) ||","sourceCodeStart":28,"sourceCodeEnd":64,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/bulk/ordered.ts#L28-L64","documentation":"Thrown as MongoInvalidArgumentError by OrderedBulkOperation.addToOperationsList() (src/bulk/ordered.ts:46) when a single operation document serializes to a BSON size greater than or equal to maxBsonObjectSize (16 MiB by default, returned by the server in the hello/handshake). The driver serializes the document up front to compute its size and rejects oversized ops before sending them, so the server never sees them.","triggerScenarios":"Adding an insert/update/replacement document whose serialized size is >= maxBsonObjectSize (e.g. embedding a large binary/blob inline). Guarded by `if (bsonSize >= this.s.maxBsonObjectSize)` at src/bulk/ordered.ts:44.","commonSituations":"Storing large files/images inline instead of via GridFS, deeply nested structures, large arrays of embedded subdocuments, or a server whose maxBsonObjectSize was lowered. Also seen when a document grew organically past 16 MiB.","solutions":["Move large binary payloads to GridFS (bucket.uploadFromStream) or an object store and keep only a reference in the document.","Trim or normalize embedded arrays and nested subdocuments that bloated the document.","Confirm the server's actual limit (db.hello().maxBsonObjectSize) — it is normally 16777216; if a custom server reports less, size accordingly.","Split a single huge update into per-field updates or stage the data in a side collection."],"exampleFix":"// before: inline blob blows past 16 MiB\nbulk.insert({ _id: 1, data: hugeBuffer });\nawait bulk.execute();\n\n// after: store blob via GridFS, keep only metadata\nconst bucket = new MongoClient(uri).db().bucket();\nconst streamId = await new Promise((resolve, reject) => {\n  const up = bucket.openUploadStream();\n  up.end(hugeBuffer, () => resolve(up.id));\n  up.on('error', reject);\n});\nbulk.insert({ _id: 1, fileId: streamId });\nawait bulk.execute();","handlingStrategy":"validation","validationCode":"import { serialize } from 'bson';\n\nconst MAX_BSON = 16 * 1024 * 1024; // 16 MiB default; confirm with db.hello().maxBsonObjectSize\n\nfunction isWithinBsonLimit(doc: unknown): boolean {\n  try {\n    return serialize(doc as Record<string, unknown>).length < MAX_BSON;\n  } catch {\n    return false;\n  }\n}\n\nfor (const op of ops) {\n  const doc = 'insertOne' in op ? op.insertOne.document : undefined;\n  if (doc && !isWithinBsonLimit(doc)) {\n    throw new Error('document exceeds 16 MiB BSON limit; move large payloads to GridFS');\n  }\n}","typeGuard":"function isReasonablySmallDoc(doc: unknown, max = 16 * 1024 * 1024): boolean {\n  try {\n    return serialize(doc as Record<string, unknown>).length < max;\n  } catch {\n    return false;\n  }\n}","tryCatchPattern":"try {\n  await bulk.execute();\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /larger than the maximum size/.test(e.message)) {\n    // offload large binary fields to GridFS, then rebuild and re-execute\n  } else throw e;\n}","preventionTips":["Store large binaries via GridFS rather than inline document fields.","Cap embedded arrays and normalize deeply nested subdocuments.","Confirm db.hello().maxBsonObjectSize on the target server (normally 16 MiB).","Add a pre-write size check using bson.serialize().length for user-supplied payloads.","Split very large updates into smaller per-field updates or stage data in a side collection."],"tags":["bulk-write","ordered","bson-size","limits","validation"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}