如何在MongoDB中正确执行Bulk upsert / update

我试图:

  • 根据search条件查找文档,
  • 如果find,更新一些属性
  • 如果不插入具有某些属性的文档。

我正在使用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 teamName: home.team.name, // String userId: home.iduser, // String userName: home.user.name, // String round: 0, signupPoints: home.signupPoints, // String lfPoints: roundPoints+home.signupPoints, // Number roundPoints: [roundPoints] // Number }; 

这是我想要插入/更新:

 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,也使用mongodb本地驱动程序的JS代码。

你的语法基本上是正确的,但是你的一般执行是错误的,你应该从其他修改中“分离”“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驱动程序,这是很好的。

通常,我一直将upsert设置为更新的属性。 也更新应该能够findlogging本身,所以不需要单独find它。

$根据环境可能或可能不需要。

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