如何在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 });
- 如何不保存在Mongoose中的某个字段?
- 在Heroku上部署Nodejs + MongoDB,但安装附加组件时需要validation信用卡
- Mongoose.findOneAndUpdate()不创build新文档
- mongodb mongoose nodejs express4为什么自动在Object Array字段中插入一个_id?
- 如何在节点js中创buildpdf文件
- ES6 – 如何导入连接mongo(会话)?
- 在聚合过程中,mongoose / mongodb是否可以访问模式中的对象引用?
- 如何使用$ push查询将数据插入到子文档中,而不是检索文档并将其保存回来
- dynamic查询MongoDB