简短回答:
Using updateMany
至少快两倍,但可能会意外更新比您预期更多的文档,请继续阅读以了解如何避免这种情况并获得性能优势。
长答案:
我们进行了以下实验来了解答案,步骤如下:
- 创建一个银行账户mongodb集合,每个文档只包含一个字段(余额)。
- 将 100 万个文档插入银行账户收藏。
- 随机化所有 100 万个文档在内存中的顺序,以避免使用以相同顺序插入的 id 进行数据库中任何可能的优化,从而模拟真实场景。
- 使用 0 到 100 之间的随机数从文档构建bulkWrite 的写入操作。
- 执行批量写入。
- 记录bulkWrite 所花费的时间。
现在,实验进行到第四步。
在实验的一个变体中,我们构建了一个包含 100 万个的数组updateOne
操作,每个updateOne
has filter
对于单个文档及其各自的“更新对象”。
在第二个变体中,我们构建了 100updateMany
操作,每个操作包括filter
对于 10K 文档 ID,以及它们各自的update
.
Results:
updateMany
具有多个文档 ID 比多个文档 ID 快 243%updateOne
s,但这不能在任何地方使用,请阅读“风险”部分以了解何时应使用它.
Details:我们对每个变体运行脚本 5 次,详细结果如下:
使用 updateOne:平均 51.28 秒。
使用 updateMany:平均 21.04 秒。
风险:正如很多人已经指出的那样,updateMany
不是直接替代updateOne
,因为当我们的意图是真正只更新一个文档时,它可能会错误地更新多个文档。
此方法仅在您使用唯一的字段(例如_id
或任何其他唯一的字段,如果过滤器依赖于不唯一的字段,则多个文档将被更新,并且结果将不相等。
65831219.js
// 65831219.js
'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
const DOCUMENTS_COUNT = 1_000_000;
const UPDATE_MANY_OPERATIONS_COUNT = 100;
const MINIMUM_BALANCE = 0;
const MAXIMUM_BALANCE = 100;
const SAMPLES_COUNT = 10;
const bankAccountSchema = new Schema({
balance: { type: Number }
});
const BankAccount = mongoose.model('BankAccount', bankAccountSchema);
mainRunner().catch(console.error);
async function mainRunner () {
for (let i = 0; i < SAMPLES_COUNT; i++) {
await runOneCycle(buildUpdateManyWriteOperations).catch(console.error);
await runOneCycle(buildUpdateOneWriteOperations).catch(console.error);
console.log('-'.repeat(80));
}
process.exit(0);
}
/**
*
* @param {buildUpdateManyWriteOperations|buildUpdateOneWriteOperations} buildBulkWrite
*/
async function runOneCycle (buildBulkWrite) {
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
await mongoose.connection.dropDatabase();
const { accounts } = await createAccounts({ accountsCount: DOCUMENTS_COUNT });
const { writeOperations } = buildBulkWrite({ accounts });
const writeStartedAt = Date.now();
await BankAccount.bulkWrite(writeOperations);
const writeEndedAt = Date.now();
console.log(`Write operations took ${(writeEndedAt - writeStartedAt) / 1000} seconds with \`${buildBulkWrite.name}\`.`);
}
async function createAccounts ({ accountsCount }) {
const rawAccounts = Array.from({ length: accountsCount }, () => ({ balance: getRandomInteger(MINIMUM_BALANCE, MAXIMUM_BALANCE) }));
const accounts = await BankAccount.insertMany(rawAccounts);
return { accounts };
}
function buildUpdateOneWriteOperations ({ accounts }) {
const writeOperations = shuffleArray(accounts).map((account) => ({
updateOne: {
filter: { _id: account._id },
update: { balance: getRandomInteger(MINIMUM_BALANCE, MAXIMUM_BALANCE) }
}
}));
return { writeOperations };
}
function buildUpdateManyWriteOperations ({ accounts }) {
shuffleArray(accounts);
const accountsChunks = chunkArray(accounts, accounts.length / UPDATE_MANY_OPERATIONS_COUNT);
const writeOperations = accountsChunks.map((accountsChunk) => ({
updateMany: {
filter: { _id: { $in: accountsChunk.map(account => account._id) } },
update: { balance: getRandomInteger(MINIMUM_BALANCE, MAXIMUM_BALANCE) }
}
}));
return { writeOperations };
}
function getRandomInteger (min = 0, max = 1) {
min = Math.ceil(min);
max = Math.floor(max);
return min + Math.floor(Math.random() * (max - min + 1));
}
function shuffleArray (array) {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function chunkArray (array, sizeOfTheChunkedArray) {
const chunked = [];
for (const element of array) {
const last = chunked[chunked.length - 1];
if (!last || last.length === sizeOfTheChunkedArray) {
chunked.push([element]);
} else {
last.push(element);
}
}
return chunked;
}
Output
$ node 65831219.js
Write operations took 20.803 seconds with `buildUpdateManyWriteOperations`.
Write operations took 50.84 seconds with `buildUpdateOneWriteOperations`.
----------------------------------------------------------------------------------------------------
测试使用运行MongoDB版本 4.0.4.