{"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":"validation","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/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/bulk/ordered.ts#L28-L64","documentation":"Thrown by OrderedBulkOperation.addToOperationsList() when a single operation's serialized BSON size is >= the server's maxBsonObjectSize (typically 16MB, learned from the server at handshake). The check fires before the op is added to a batch; oversized documents cannot be sent to MongoDB and must be reduced or stored differently (e.g. GridFS).","triggerScenarios":"Inserting a document with a large embedded binary/text field via bulk.insert(). Updating with a multi-megabyte $set value. Pushing large arrays via $push.","commonSituations":"Loading large media or log blobs inline; serializing large nested structures; migrating from a store with no size limit.","solutions":["Reduce document size: store large blobs in GridFS or an object store and keep only a reference in the document.","Split the document or chunk the payload across multiple documents.","Confirm maxBsonObjectSize from the server (coll.s.db.client.s.options / hello response) to know your actual limit."],"exampleFix":"// before\nbulk.insert({ data: hugeBuffer }); // hugeBuffer > 16MB\n\n// after\n// store large content out-of-band, keep a reference\nconst id = await bucket.upload(hugeBuffer);\nbulk.insert({ contentId: id, metadata: {...} });","handlingStrategy":"validation","validationCode":"import * as BSON from 'bson';\nfunction assertUnderMaxSize(doc, maxBsonObjectSize = 16 * 1024 * 1024) {\n  const size = BSON.serialize(doc).length;\n  if (size >= maxBsonObjectSize) {\n    throw new RangeError(`document serialized to ${size} bytes, exceeds ${maxBsonObjectSize}`);\n  }\n}","typeGuard":"function isWithinBsonLimit(doc, maxBsonObjectSize = 16 * 1024 * 1024) {\n  try {\n    return BSON.serialize(doc).length < maxBsonObjectSize;\n  } catch {\n    return false;\n  }\n}","tryCatchPattern":"try {\n  bulk.insert(doc);\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /larger than the maximum size/.test(e.message)) {\n    // route to GridFS or chunk the document\n  }\n}","preventionTips":["Cap inline blob fields; route large payloads through GridFS or external storage.","Pre-serialize and measure documents when ingesting untrusted/large data.","Read maxBsonObjectSize from the server hello rather than hardcoding."],"tags":["bulk-write","ordered","bson","size-limit"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}