Hi @Joseph_Gan,
I found that updateMany() is a wrapper for bulk write by using the Mongo Shell.
I typed
db.foo.updateMany
and the following was returned:
function(filter, update, options) {
var opts = Object.extend({}, options || {});
// Pipeline updates are always permitted. Otherwise, we validate the update object.
if (!Array.isArray(update)) {
// Check if first key in update statement contains a $
var keys = Object.keys(update);
if (keys.length == 0) {
throw new Error(
"the update operation document must contain at least one atomic operator");
}
// Check if first key does not have the $
if (keys[0][0] != "$") {
throw new Error('the update operation document must contain atomic operators');
}
}
// Get the write concern
var writeConcern = this._createWriteConcern(opts);
// Result
var result = {acknowledged: (writeConcern && writeConcern.w == 0) ? false : true};
// Use bulk operation API already in the shell
var bulk = this.initializeOrderedBulkOp();
// Add the updateMany operation
var op = bulk.find(filter);
if (opts.upsert) {
op = op.upsert();
}
if (opts.collation) {
op.collation(opts.collation);
}
if (opts.arrayFilters) {
op.arrayFilters(opts.arrayFilters);
}
op.update(update);
try {
// Update all documents that match the selector
var r = bulk.execute(writeConcern);
} catch (err) {
if (err instanceof BulkWriteError) {
if (err.hasWriteErrors()) {
throw err.getWriteErrorAt(0);
}
if (err.hasWriteConcernError()) {
throw err.getWriteConcernError();
}
}
throw err;
}
if (!result.acknowledged) {
return result;
}
result.matchedCount = r.nMatched;
result.modifiedCount = (r.nModified != null) ? r.nModified : r.n;
if (r.getUpsertedIds().length > 0) {
result.upsertedId = r.getUpsertedIdAt(0)._id;
}
return result;
}
For more information about bulkWrite, visit https://docs.mongodb.com/manual/core/bulk-write-operations/. For more information about updateMany, visit https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/index.html.
If you want to update many documents, you can choose to use bulkWrite or updateMany and you’ll get the same performance.
Regarding concurrency: I see what you mean now.
MongoDB intelligently handles locking for you. If you have two simultaneous transactions that touch the same document, one transaction will occur before the other. You have two options.
- You can pull the latest copy of the document, make changes to it, and send it back to the database.
- You can choose to update only the fields you want to update.
See https://docs.mongodb.com/manual/faq/concurrency/ for more details.