【问题标题】:Upsert does not work for updateOne bulkWrite v3.4Upsert 不适用于 updateOne bulkWrite v3.4
【发布时间】:2018-05-29 15:24:00
【问题描述】:

我正在尝试批量编写一些更新,并且除了 upsert 之外的所有内容都可以正常工作。
我的代码完美地更新了所有项目,并且没有给出任何错误。
这里的问题是带有updateOne 的批量插入没有更新插入。

(这是我的代码的未经测试且经过简化的示例,因此您可能会发现一些语法错误。希望您明白这一点。)

async function insert(items) {
    const ops = items.map(item => ({
        updateOne: {
            filter: {
                id: item.id,
                country: item.country,
            },
            update: { $set: item },
            upsert: true
        }
    }));

    return await db.collection.bulkWrite(ops);
}

insert([{
    id: '123',
    country: 'uk',
    email: 'test@test.com'
}]);

上面的 sn-p 不会更新丢失的项目,而是正确更新其他所有内容。

我正在使用 node version 6.6.0mongodb version v3.4.10,因此根据 mongodb 文档 3.4 (https://docs.mongodb.com/v3.4/reference/method/db.collection.bulkWrite/),bulkwrite 是 3.2 版中的新功能。

这个 sn-p 来自 bulkWrite 的 MongoDB 3.4 文档。

db.collection.bulkWrite( [
   { updateOne :
      {
         "filter" : <document>,
         "update" : <document>,
         "upsert" : <boolean>
      }
   }
] )

这是来自同一文档的示例。

{
    updateOne: {
        "filter": { "char": "Eldon" },
        "update": { $set: { "status": "Critical Injury" } }
    }
}

我已尝试直接在 mongo 终端界面中使用完全相同的数据进行正常更新,并正确更新了项目。

db.collection.update({ id: '123', country: 'uk' }, { $set: { id: '123', country: 'uk', email: 'test@test.com' } }, { upsert: true });

【问题讨论】:

  • 你可以试试: const ops = items.map(item => ({ updateOne: { filter: { id: item.id, country: item.country, }, update: { $set : {item} }, upsert: true } }));
  • 天哪,这真的有效吗?!愿意在答案中解释原因以便我接受吗?

标签: node.js mongodb


【解决方案1】:
const ops = items.map(item => 
           ({ updateOne: { 
              filter: { id: item.id, country: item.country}, 
              update: { $set: {item} }, upsert: true } 
           }));

$set 按语法要求 { id: item.id, country: item.country} 而不仅仅是 id: item.id, country: item .country 正在通过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2020-09-04
    • 2021-07-06
    • 1970-01-01
    • 2020-02-18
    • 2020-09-06
    • 2021-08-30
    相关资源
    最近更新 更多