【问题标题】:Update batch documents if exist else insert in MongoDB如果存在则更新批处理文档,否则在 MongoDB 中插入
【发布时间】:2020-04-24 18:43:13
【问题描述】:

我在数组中有一组文档,如果我使用 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' };
    });

【问题讨论】:

    标签: mongodb mongodb-query nosql


    【解决方案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)
    

    【讨论】:

    • 有一个错误:bulkWrite只支持insertOne、insertMany、updateOne、updateMany、removeOne、removeMany、deleteOne、deleteMany
    猜你喜欢
    • 2014-02-16
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2021-06-03
    • 2014-10-23
    • 2013-04-19
    • 2015-08-14
    相关资源
    最近更新 更多