How to properly do a Bulk upsert/update in MongoDB

前端 未结 3 633
梦毁少年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:26

    Your syntax here is basically correct, but your general execution was wrong and you should have "seperated" the "upsert" action from the other modifications. These will otherwise "clash" and produce an error when an "upsert" occurs:

    LineupPointsRecord.native(function (err,collection) {
    
        var bulk = collection.initializeOrderedBulkOp();
    
        // Match and update only. Do not attempt upsert
        bulk.find({
            "teamId": lineUpPointsGeneralRecord.teamId,
            "round": 0
        }).updateOne({
            "$inc": { "lfPoints": roundPoints },
            "$push": { "roundPoints": roundPoints }
        });
    
        // Attempt upsert with $setOnInsert only
        bulk.find({
            "teamId": lineUpPointsGeneralRecord.teamId,
            "round": 0
        }).upsert().updateOne({
            "$setOnInsert": lineUpPointsGeneralRecord
        });
    
        bulk.execute(function (err,updateResult) {
            sails.log.debug(err,updateResult);
        });
    });
    

    Make sure your sails-mongo is a latest version supporting the Bulk operations properly be the inclusion of a recent node native driver. The most recent supports the v2 driver, which is fine for this.

提交回复
热议问题