【发布时间】: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.0 和 mongodb 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 } }));
-
天哪,这真的有效吗?!愿意在答案中解释原因以便我接受吗?