首页 > 解决方案 > MongoDB bulkWrite multiple updateOne vs updateMany

问题描述

我在某些情况下构建 bulkWrite 操作,其中某些文档具有相同的update对象,合并过滤器并发送一个updateMany与这些过滤器而不是多个updateOnes是否有任何性能优势bulkWrite

updateMany使用普通方法时使用多个s显然更好updateOne,但是使用 bulkWrite,因为它是一个命令,所以优先使用一个命令有什么显着的好处吗?

例子:

我有 200k 文档需要更新,status所有 200K 文档共有 10 个唯一字段,所以我的选择是:

解决方案:

A)发送一个包含 10 个updateMany操作的 bulkWrite,每个操作都会影响 20K 文档。

B)发送一个单独的 bulkWrite,updateOne每个操作持有其过滤器和200K status

正如@AlexBlex 指出的那样,我必须小心使用相同的过滤器意外更新多个文档,在我的情况下,我将_id其用作我的过滤器,因此在我的情况下,意外更新其他文档不是问题,但绝对值得一看在考虑updateMany选项时。

谢谢@AlexBlex。

标签: mongodbdatabase-performance

解决方案


简短的回答:

使用updateMany速度至少快两倍,但可能会意外更新比您预期更多的文档,请继续阅读以了解如何避免这种情况并获得性能优势。

长答案:

我们进行了以下实验以了解答案,以下是步骤:

  1. 创建一个bankaccounts mongodb 集合,每个文档只包含一个字段(余额)。
  2. 将 100 万份文件插入银行账户集合。
  3. 随机化所有 100 万个文档在内存中的顺序,以避免使用以相同顺序插入的 id 对数据库进行任何可能的优化,模拟真实场景。
  4. 从具有 0 到 100 之间随机数的文档构建 bulkWrite 的写入操作。
  5. 执行批量写入。
  6. 记录 bulkWrite 花费的时间。

现在,实验处于第四步。

在实验的一个变体中,我们构建了一个包含 100 万个updateOne操作的数组,每个操作updateOne都有filter一个文档,以及它各自的“更新对象”。

在第二个变体中,我们构建了 100 个updateMany操作,每个操作包括filter10K 个文档 ID,以及它们各自的update.

结果: updateMany多文档 id 比多updateOnes 快 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 版运行测试。


推荐阅读