{"record":{"id":"2cfc8e5bcd8da5ac","repo":"mongodb/node-mongodb-native","slug":"document-is-larger-than-the-maximum-size-this-s-2cfc8e","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/unordered.ts","lineNumber":60,"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\n    // Holds the current batch\n    this.s.currentBatch = undefined;\n    // Get the right type of batch\n    if (batchType === BatchType.INSERT) {\n      this.s.currentBatch = this.s.currentInsertBatch;\n    } else if (batchType === BatchType.UPDATE) {\n      this.s.currentBatch = this.s.currentUpdateBatch;\n    } else if (batchType === BatchType.DELETE) {\n      this.s.currentBatch = this.s.currentRemoveBatch;\n    }\n\n    const maxKeySize = this.s.maxKeySize;\n\n    // Create a new batch object if we don't have a current one","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/bulk/unordered.ts#L42-L78","documentation":"Thrown as MongoInvalidArgumentError by UnorderedBulkOperation.addToOperationsList() (src/bulk/unordered.ts:60) when a single operation document serializes to a BSON size greater than or equal to maxBsonObjectSize (16 MiB default). Same contract as error 17, but on the unordered bulk path.","triggerScenarios":"Adding an oversized insert/update/replacement document to an unordered bulk op. Guarded by `if (bsonSize >= this.s.maxBsonObjectSize)` at src/bulk/unordered.ts:58.","commonSituations":"Inline binary blobs instead of GridFS, oversized embedded arrays/nested objects, documents that grew past 16 MiB over time, or targeting a server with a lowered maxBsonObjectSize.","solutions":["Move large binary payloads to GridFS or an external object store and keep a reference.","Trim/normalize embedded arrays and deeply nested subdocuments.","Verify db.hello().maxBsonObjectSize on the target server and size accordingly.","Split a huge update into smaller per-field updates or stage the data in a side collection."],"exampleFix":"// before: inline blob blows past 16 MiB\nconst bulk = coll.initializeUnorderedBulkOp();\nbulk.insert({ _id: 1, data: hugeBuffer });\nawait bulk.execute();\n\n// after: store blob via GridFS, keep only metadata\nconst bucket = 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});\nconst bulk = coll.initializeUnorderedBulkOp();\nbulk.insert({ _id: 1, fileId: streamId });\nawait bulk.execute();","handlingStrategy":"validation","validationCode":"import { serialize } from 'bson';\n\nconst MAX_BSON = 16 * 1024 * 1024; // 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","unordered","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"}