3 var common = require('./common')
4 , utils = require('../utils')
5 , toError = require('../utils').toError
6 , f = require('util').format
7 , handleCallback = require('../utils').handleCallback
8 , shallowClone = utils.shallowClone
9 , WriteError = common.WriteError
10 , BulkWriteResult = common.BulkWriteResult
11 , LegacyOp = common.LegacyOp
12 , ObjectID = require('mongodb-core').BSON.ObjectID
13 , BSON = require('mongodb-core').BSON
14 , Define = require('../metadata')
15 , Batch = common.Batch
16 , mergeBatchResults = common.mergeBatchResults;
18 var bson = new BSON.BSONPure();
21 * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly)
23 * @property {number} length Get the number of operations in the bulk.
24 * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance.
26 var FindOperatorsUnordered = function(self) {
31 * Add a single update document to the bulk operation
34 * @param {object} doc update operations
35 * @throws {MongoError}
36 * @return {UnorderedBulkOperation}
38 FindOperatorsUnordered.prototype.update = function(updateDocument) {
40 var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false;
42 // Establish the update command
44 q: this.s.currentOp.selector
50 // Clear out current Op
51 this.s.currentOp = null;
52 // Add the update document to the list
53 return addToOperationsList(this, common.UPDATE, document);
57 * Add a single update one document to the bulk operation
60 * @param {object} doc update operations
61 * @throws {MongoError}
62 * @return {UnorderedBulkOperation}
64 FindOperatorsUnordered.prototype.updateOne = function(updateDocument) {
66 var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false;
68 // Establish the update command
70 q: this.s.currentOp.selector
76 // Clear out current Op
77 this.s.currentOp = null;
78 // Add the update document to the list
79 return addToOperationsList(this, common.UPDATE, document);
83 * Add a replace one operation to the bulk operation
86 * @param {object} doc the new document to replace the existing one with
87 * @throws {MongoError}
88 * @return {UnorderedBulkOperation}
90 FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) {
91 this.updateOne(updateDocument);
95 * Upsert modifier for update bulk operation
98 * @throws {MongoError}
99 * @return {UnorderedBulkOperation}
101 FindOperatorsUnordered.prototype.upsert = function() {
102 this.s.currentOp.upsert = true;
107 * Add a remove one operation to the bulk operation
110 * @throws {MongoError}
111 * @return {UnorderedBulkOperation}
113 FindOperatorsUnordered.prototype.removeOne = function() {
114 // Establish the update command
116 q: this.s.currentOp.selector
120 // Clear out current Op
121 this.s.currentOp = null;
122 // Add the remove document to the list
123 return addToOperationsList(this, common.REMOVE, document);
127 * Add a remove operation to the bulk operation
130 * @throws {MongoError}
131 * @return {UnorderedBulkOperation}
133 FindOperatorsUnordered.prototype.remove = function() {
134 // Establish the update command
136 q: this.s.currentOp.selector
140 // Clear out current Op
141 this.s.currentOp = null;
142 // Add the remove document to the list
143 return addToOperationsList(this, common.REMOVE, document);
147 // Add to the operations list
149 var addToOperationsList = function(_self, docType, document) {
151 var bsonSize = bson.calculateObjectSize(document, false);
152 // Throw error if the doc is bigger than the max BSON size
153 if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes);
154 // Holds the current batch
155 _self.s.currentBatch = null;
156 // Get the right type of batch
157 if(docType == common.INSERT) {
158 _self.s.currentBatch = _self.s.currentInsertBatch;
159 } else if(docType == common.UPDATE) {
160 _self.s.currentBatch = _self.s.currentUpdateBatch;
161 } else if(docType == common.REMOVE) {
162 _self.s.currentBatch = _self.s.currentRemoveBatch;
165 // Create a new batch object if we don't have a current one
166 if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex);
168 // Check if we need to create a new batch
169 if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize)
170 || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes)
171 || (_self.s.currentBatch.batchType != docType)) {
172 // Save the batch to the execution stack
173 _self.s.batches.push(_self.s.currentBatch);
175 // Create a new batch
176 _self.s.currentBatch = new Batch(docType, _self.s.currentIndex);
179 // We have an array of documents
180 if(Array.isArray(document)) {
181 throw toError("operation passed in cannot be an Array");
183 _self.s.currentBatch.operations.push(document);
184 _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex);
185 _self.s.currentIndex = _self.s.currentIndex + 1;
188 // Save back the current Batch to the right type
189 if(docType == common.INSERT) {
190 _self.s.currentInsertBatch = _self.s.currentBatch;
191 _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id});
192 } else if(docType == common.UPDATE) {
193 _self.s.currentUpdateBatch = _self.s.currentBatch;
194 } else if(docType == common.REMOVE) {
195 _self.s.currentRemoveBatch = _self.s.currentBatch;
198 // Update current batch size
199 _self.s.currentBatch.size = _self.s.currentBatch.size + 1;
200 _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize;
207 * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
209 * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance.
211 var UnorderedBulkOperation = function(topology, collection, options) {
212 options = options == null ? {} : options;
214 // Contains reference to self
216 // Get the namesspace for the write operations
217 var namespace = collection.collectionName;
218 // Used to mark operation as executed
219 var executed = false;
222 // var currentBatch = null;
223 var currentOp = null;
224 var currentIndex = 0;
227 // The current Batches for the different operations
228 var currentInsertBatch = null;
229 var currentUpdateBatch = null;
230 var currentRemoveBatch = null;
232 // Handle to the bson serializer, used to calculate running sizes
233 var bson = topology.bson;
236 var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize
237 ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16);
238 var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize
239 ? topology.isMasterDoc.maxWriteBatchSize : 1000;
241 // Get the write concern
242 var writeConcern = common.writeConcern(shallowClone(options), collection, options);
244 // Get the promiseLibrary
245 var promiseLibrary = options.promiseLibrary;
247 // No promise library selected fall back
248 if(!promiseLibrary) {
249 promiseLibrary = typeof global.Promise == 'function' ?
250 global.Promise : require('es6-promise').Promise;
257 , writeConcernErrors: []
270 bulkResult: bulkResult
271 // Current batch state
272 , currentInsertBatch: null
273 , currentUpdateBatch: null
274 , currentRemoveBatch: null
279 , writeConcern: writeConcern
280 // Max batch size options
281 , maxBatchSizeBytes: maxBatchSizeBytes
282 , maxWriteBatchSize: maxWriteBatchSize
284 , namespace: namespace
292 , currentOp: currentOp
296 , collection: collection
298 , promiseLibrary: promiseLibrary
300 , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false
304 var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false);
307 * Add a single insert document to the bulk operation
309 * @param {object} doc the document to insert
310 * @throws {MongoError}
311 * @return {UnorderedBulkOperation}
313 UnorderedBulkOperation.prototype.insert = function(document) {
314 if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID();
315 return addToOperationsList(this, common.INSERT, document);
319 * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
322 * @param {object} selector The selector for the bulk operation.
323 * @throws {MongoError}
324 * @return {FindOperatorsUnordered}
326 UnorderedBulkOperation.prototype.find = function(selector) {
328 throw toError("Bulk find operation must specify a selector");
331 // Save a current selector
336 return new FindOperatorsUnordered(this);
339 Object.defineProperty(UnorderedBulkOperation.prototype, 'length', {
342 return this.s.currentIndex;
346 UnorderedBulkOperation.prototype.raw = function(op) {
347 var key = Object.keys(op)[0];
349 // Set up the force server object id
350 var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean'
351 ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId;
354 if((op.updateOne && op.updateOne.q)
355 || (op.updateMany && op.updateMany.q)
356 || (op.replaceOne && op.replaceOne.q)) {
357 op[key].multi = op.updateOne || op.replaceOne ? false : true;
358 return addToOperationsList(this, common.UPDATE, op[key]);
361 // Crud spec update format
362 if(op.updateOne || op.updateMany || op.replaceOne) {
363 var multi = op.updateOne || op.replaceOne ? false : true;
364 var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi}
365 if(op[key].upsert) operation.upsert = true;
366 return addToOperationsList(this, common.UPDATE, operation);
370 if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) {
371 op[key].limit = op.removeOne ? 1 : 0;
372 return addToOperationsList(this, common.REMOVE, op[key]);
375 // Crud spec delete operations, less efficient
376 if(op.deleteOne || op.deleteMany) {
377 var limit = op.deleteOne ? 1 : 0;
378 var operation = {q: op[key].filter, limit: limit}
379 return addToOperationsList(this, common.REMOVE, operation);
383 if(op.insertOne && op.insertOne.document == null) {
384 if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID();
385 return addToOperationsList(this, common.INSERT, op.insertOne);
386 } else if(op.insertOne && op.insertOne.document) {
387 if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID();
388 return addToOperationsList(this, common.INSERT, op.insertOne.document);
392 for(var i = 0; i < op.insertMany.length; i++) {
393 if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID();
394 addToOperationsList(this, common.INSERT, op.insertMany[i]);
400 // No valid type of operation
401 throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany");
405 // Execute the command
406 var executeBatch = function(self, batch, callback) {
407 var finalOptions = {ordered: false}
408 if(self.s.writeConcern != null) {
409 finalOptions.writeConcern = self.s.writeConcern;
412 var resultHandler = function(err, result) {
413 // Error is a driver related error not a bulk op error, terminate
414 if(err && err.driver || err && err.message) {
415 return handleCallback(callback, err);
418 // If we have and error
420 handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result));
423 // Set an operationIf if provided
424 if(self.operationId) {
425 resultHandler.operationId = self.operationId;
428 // Serialize functions
429 if(self.s.options.serializeFunctions) {
430 finalOptions.serializeFunctions = true
433 // Is the bypassDocumentValidation options specific
434 if(self.s.bypassDocumentValidation == true) {
435 finalOptions.bypassDocumentValidation = true;
439 if(batch.batchType == common.INSERT) {
440 self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
441 } else if(batch.batchType == common.UPDATE) {
442 self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
443 } else if(batch.batchType == common.REMOVE) {
444 self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler);
447 // Force top level error
449 // Merge top level error and return
450 handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null));
455 // Execute all the commands
456 var executeBatches = function(self, callback) {
457 var numberOfCommandsToExecute = self.s.batches.length;
459 // Execute over all the batches
460 for(var i = 0; i < self.s.batches.length; i++) {
461 executeBatch(self, self.s.batches[i], function(err, result) {
462 // Driver layer error capture it
464 // Count down the number of commands left to execute
465 numberOfCommandsToExecute = numberOfCommandsToExecute - 1;
468 if(numberOfCommandsToExecute == 0) {
469 // Driver level error
470 if(error) return handleCallback(callback, error);
471 // Treat write errors
472 var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null;
473 handleCallback(callback, error, new BulkWriteResult(self.s.bulkResult));
480 * The callback format for results
481 * @callback UnorderedBulkOperation~resultCallback
482 * @param {MongoError} error An error instance representing the error during the execution.
483 * @param {BulkWriteResult} result The bulk write result.
487 * Execute the ordered bulk operation
490 * @param {object} [options=null] Optional settings.
491 * @param {(number|string)} [options.w=null] The write concern.
492 * @param {number} [options.wtimeout=null] The write concern timeout.
493 * @param {boolean} [options.j=false] Specify a journal write concern.
494 * @param {boolean} [options.fsync=false] Specify a file sync write concern.
495 * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback
496 * @throws {MongoError}
497 * @return {Promise} returns Promise if no callback passed
499 UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) {
501 if(this.s.executed) throw toError("batch cannot be re-executed");
502 if(typeof _writeConcern == 'function') {
503 callback = _writeConcern;
505 this.s.writeConcern = _writeConcern;
508 // If we have current batch
509 if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
510 if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
511 if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
513 // If we have no operations in the bulk raise an error
514 if(this.s.batches.length == 0) {
515 throw toError("Invalid Operation, No operations in bulk");
518 // Execute using callback
519 if(typeof callback == 'function') return executeBatches(this, callback);
522 return new this.s.promiseLibrary(function(resolve, reject) {
523 executeBatches(self, function(err, r) {
524 if(err) return reject(err);
530 define.classMethod('execute', {callback: true, promise:false});
533 * Returns an unordered batch object
536 var initializeUnorderedBulkOp = function(topology, collection, options) {
537 return new UnorderedBulkOperation(topology, collection, options);
540 initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation;
541 module.exports = initializeUnorderedBulkOp;
542 module.exports.Bulk = UnorderedBulkOperation;