How to properly do a Bulk upsert/update in MongoDB

前端 未结 3 623
梦毁少年i
梦毁少年i 2020-12-10 14:53

I\'m trying to:

  • Find a document according to a search criteria,
  • If found, update some attributes
  • If not insert a document with some attribut
3条回答
  •  执念已碎
    2020-12-10 15:44

    I recommend use bulkWrite exemplary code with bulk upsert of many documents:

    In this case you will create documents with unique md5. If document exists then will be updated but no new document is created like in classical insertMany.

    const collection = context.services.get("mongodb-atlas").db("master").collection("fb_posts");
    
    return collection.bulkWrite(
      posts.map(p => { 
        return { updateOne:
          {
            filter: { md5: p.md5 },
            update: {$set: p},
            upsert : true
          }
        }
      }
      ),
      { ordered : false }
    );
    

    https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/

提交回复
热议问题