更新批处理文档(如果存在),否则插入MongoDB

时间:2020-04-24 18:43:13

标签: mongodb mongodb-query nosql

我在数组中有一组文档,如果与insertMany查询一起使用,效果很好。现在,我想在查询中添加条件,如果该文档以相同的 product_ID 存在,请对其进行更新。如何通过updateMany使用文档数组。我不想一一使用更新。

文档数组: First time Insert

[
{_id:"5ea0428e5f725d00079afaab", product_id:345, title:"Car"},
{_id:"5e40428e5f725d00079afa4b", product_id:456, title:"Ball"},
{_id:"5e60428e5f725d00079afaab", product_id:555, title:"Dog"},
]

这样的预期代码: Second time update,因为product_id已经存在。

  return db.collection("cars").updateMany([
    {_id:"5ea0428e5f725d00079afaab", product_id:345, title:"Hen"},
    {_id:"5e40428e5f725d00079afa4b", product_id:456, title:"Cow"},
    {_id:"5e60428e5f725d00079afaab", product_id:555, title:"Goat"},
    ]).then((items) => { 
    return { statusCode: 200, body: items }; })
    .catch(err => {
      console.log('=> an error occurred: ', err);
      return { statusCode: 500, body: 'error' };
    });

1 个答案:

答案 0 :(得分:1)

您可以将.map()数组replaceOne个数组组成,然后使用bulkWrite执行它们。请注意,您传递的_id无论如何都必须是唯一的:

var data = [
{_id:"5ea0428e5f725d00079afaab", product_id:345, title:"Car"},
{_id:"5e40428e5f725d00079afa4b", product_id:456, title:"Ball"},
{_id:"5e60428e5f725d00079afaab", product_id:555, title:"Dog"},
];

var upserts = data.map(doc => ({
    "replaceOne": {
        filter: { product_id: doc.product_id} ,
        replacement: doc,
        upsert: true
    }
}));

console.log(upserts);

db.collection.bulkWrite(upserts)