Upsert 不适用于 updateOne bulkWrite v3.4 [英] Upsert does not work for updateOne bulkWrite v3.4

查看:51
本文介绍了Upsert 不适用于 updateOne bulkWrite v3.4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to bulk write some updates and everything except the upsert is working.
My code is updating all items perfectly and no errors is given what so ever.
The issue here is that the bulk insert with updateOne is not upserting.

(这是我的代码的未经测试和缩短的示例,因此您可能会发现一些语法错误.希望您能明白.)

(This is an untested and shortened example of my code, so you might find some syntax errors. Hopefully you get the idea.)

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'
}]);

上面的代码片段不会更新丢失的项目,但会正确更新其他所有内容.

The snippet above does not upsert the missing items, but updates everything else correctly.

我正在使用 node version 6.6.0mongodb version v3.4.10 并相应地使用 3.4 的 mongodb 文档(https://docs.mongodb.com/v3.4/reference/method/db.collection.bulkWrite/) 批量写入 3.2 版中的新功能.

I'm using node version 6.6.0 and mongodb version v3.4.10 and accordingly to the mongodb documenation for 3.4 (https://docs.mongodb.com/v3.4/reference/method/db.collection.bulkWrite/) the bulkwrite is New in version 3.2.

此片段来自 bulkWrite 的 MongoDB 3.4 文档.

This snippet is from MongoDB 3.4 documenation for bulkWrite.

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

这是同一文档中的一个示例.

And this is an example from the same documentation.

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

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

I've tried a normal update directly in the mongo terminal interface with the exact same data and an upserts the item correctly.

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 } 
           }));

$set 按语法期望 { id: item.id, country: item.country} 而不是 id: item.id, country: item.country 正在通过.

$set by syntax would expect { id: item.id, country: item.country} than just id: item.id, country: item.country being passed.

这篇关于Upsert 不适用于 updateOne bulkWrite v3.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆