mongodb - MongoDB bulkWrite multiple updateOne vs updateMany
问题描述
我在某些情况下构建 bulkWrite 操作,其中某些文档具有相同的update
对象,合并过滤器并发送一个updateMany
与这些过滤器而不是多个updateOne
s是否有任何性能优势bulkWrite
?
updateMany
使用普通方法时使用多个s显然更好updateOne
,但是使用 bulkWrite,因为它是一个命令,所以优先使用一个命令有什么显着的好处吗?
例子:
我有 200k 文档需要更新,status
所有 200K 文档共有 10 个唯一字段,所以我的选择是:
解决方案:
A)发送一个包含 10 个updateMany
操作的 bulkWrite,每个操作都会影响 20K 文档。
B)发送一个单独的 bulkWrite,updateOne
每个操作持有其过滤器和200K status
。
正如@AlexBlex 指出的那样,我必须小心使用相同的过滤器意外更新多个文档,在我的情况下,我将_id
其用作我的过滤器,因此在我的情况下,意外更新其他文档不是问题,但绝对值得一看在考虑updateMany
选项时。
谢谢@AlexBlex。
解决方案
简短的回答:
使用updateMany
速度至少快两倍,但可能会意外更新比您预期更多的文档,请继续阅读以了解如何避免这种情况并获得性能优势。
长答案:
我们进行了以下实验以了解答案,以下是步骤:
- 创建一个bankaccounts mongodb 集合,每个文档只包含一个字段(余额)。
- 将 100 万份文件插入银行账户集合。
- 随机化所有 100 万个文档在内存中的顺序,以避免使用以相同顺序插入的 id 对数据库进行任何可能的优化,模拟真实场景。
- 从具有 0 到 100 之间随机数的文档构建 bulkWrite 的写入操作。
- 执行批量写入。
- 记录 bulkWrite 花费的时间。
现在,实验处于第四步。
在实验的一个变体中,我们构建了一个包含 100 万个updateOne
操作的数组,每个操作updateOne
都有filter
一个文档,以及它各自的“更新对象”。
在第二个变体中,我们构建了 100 个updateMany
操作,每个操作包括filter
10K 个文档 ID,以及它们各自的update
.
结果:
updateMany
多文档 id 比多updateOne
s 快 243%,但这不能在任何地方都使用,请阅读“风险”部分以了解何时应该使用它。
详细信息: 我们为每个变体运行脚本 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;
}
输出
$ node 65831219.js
Write operations took 20.803 seconds with `buildUpdateManyWriteOperations`.
Write operations took 50.84 seconds with `buildUpdateOneWriteOperations`.
----------------------------------------------------------------------------------------------------
使用MongoDB 4.0.4 版运行测试。
推荐阅读
- node.js - 如何配置 JSON Server 以支持特定的查询字符串参数?
- .net-core - .NET Core (v2) Azure 函数中的默认 HttpTriggerAttribute
- c# - 2个相同的绑定....一个有效,另一个无效
- c# - 创建对象时的 CS0426 - 如何理解错误
- javascript - _ 在这种情况下是什么意思
- css - CSS 选择器将元素与至少两个类实例匹配,不包括每个类的第一个实例
- arrays - 我的复选框未在 VB 中显示我的数组
- python - 装饰一个python类,使大多数方法在条件下引发异常
- javascript - 在视口中如何播放 Youtube 和 Facebook 视频?
- discord.js - 是否可以让机器人限制对特定消息的特定反应量?