微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 如何在MongoDB中正确执行批量upsert / update

我试图:

>根据搜索条件查找文档,
>如果找到,请更新一些属性
>如果没有插入带有某些属性的文档.

我正在使用Bulk.unorderedOperation,因为我还在执行单个插入.而且我想在一次操作中再做一切DB.

然而,正在为更新/ upsert操作插入一些不会导致任何问题.

这是插入文档:

var lineUpPointsRoundRecord = {
    lineupId: lineup.id,// String
    totalPoints: roundPoints,// Number
    teamId: lineup.team,// String
    teamName: home.team.name,// String
    userId: home.iduser,// String
    userName: home.user.name,// String
    round: lineup.matchDate.round,// Number
    date: new Date()
  }

这是upsert文件

var lineUpPointsGeneralRecord = {
    teamId: lineup.team,// String 
    userName: home.user.name,// String
    round: 0,signupPoints: home.signupPoints,// String
    lfPoints: roundPoints+home.signupPoints,// Number 
    roundPoints: [roundPoints] // Number
  };

这就是我尝试upsert / update的方式:

var batch = collection.initializeUnorderedBulkOp();

batch.insert(lineUpPointsRoundRecord);

batch.find({team: lineUpPointsRoundRecord.teamId,round: 0}).
  upsert().
  update({
    $setonInsert: lineUpPointsGeneralRecord,$inc: {lfPoints: roundPoints},$push: {roundPoints: roundPoints}
  });

batch.execute(function (err,result) {
  return cb(err,result);
});

为什么不进行上传/更新?

注意

这是使用水线ORM的JS代码,它也使用mongodb本机驱动程序.

解决方法

这里的语法基本上是正确的,但是你的一般执行是错误的,你应该从其他修改中“分离”“upsert”动作.否则,当发生“upsert”时,这些将“冲突”并产生错误

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);
    });
});

确保您的sails-mongo支持批量操作的最新版本,包括最近的节点本机驱动程序.最近支持v2驱动程序,这对此很好.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐