如何对 Mongo 数据库对象数组进行批量更新,其中 json 与 id 匹配

How to do a bulk update to a Mongo DB array of objects with json matched by id

我需要使用具有 id 的对象数组更新 MongoDB 字段,需要在 JSON 对象

中使用相同的 id 更新

如果我在 MongoDB

中有这样的东西
{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          name: "ABC"
        },
        {
          id : 123,
          name: "ABCD"
        }
    ]
}

我有这样的 JSON 数据要插入 Mongo

{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          author: "ccc"
        },
        {
          id : 123,
          author: "dddd"
        }
    ]
}

更新后我需要 Mongo 集合中这样的最终数据

{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          name: "ABC",
          author: "ccc"
        },
        {
          id : 123,
          name: "ABCD",
          author: "dddd"
        }
    ]
}

您可以使用 positional update to do it one by one, and batch those updates using bulkWrite.

const data = [
  { _id: 'id1', books: [{ id: 'id1_1', author: 'author1_1' }, /* ... */] },
  /* ... */
];

const bulk = [];
for (const { _id, books } of data) {
  for (const { id, author } of books) {
    bulk.push({
      updateOne: {
        filter: { _id, 'books.id': id },
        update: { $set: { 'books.$.author': author } }
      }
    });
  }
}

// Check if bulk is not empty - it will throw otherwise.
if (bulk.length > 0) db.collection.bulkWrite(bulk);