let dbOperations = Edge.collection.initializeOrderedBulkOp()
edges.forEach(edge => {
dbOperations.find({_id: edge.id}).upsert().updateOne({
$set: {
value: edge.value
},
$setOnInsert: {
_id: edge.id
}
})
})
dbOperations.execute()
.then(result => {
console.log(result.nModified) // This shows the number of edges that is actually modified
console.log(result.getModifiedIds()) // This is what I want to achieve
})
有什么办法可以做到这一点?
从一个角度来看,答案是“不”,这是有充分理由的。
一般来说,MongoDB的“更新”操作旨在跨通常的“多个”文档工作,因此意味着符合条件的任何内容。因此,这里的一般情况是您是否要求以单数形式或通过选择来更新的内容取决于是否匹配任何内容而被更新。
在“批量”背景下,许多相同的道理也适用,因为有任何一个条件匹配与否,在这种情况下,你会得到的返回值nMatched
和nModified
repectively,因为还有一个“匹配”文件是可能性如果要修改的数据已经是修改目标的值,则不会实际更新。
nMatched
和之间的最后一个区别nModified
是“您无法可靠地执行此操作”的主要原因,因为并非所有匹配项都必须进行修改。
但是,在区分“ upsert”操作和实际的“ updates”的情况下,您可以提供一个客户评估值。由于存在明显的区别,它不会是100%准确的,但是基本过程是将输入列表与中的返回值进行比较getUpsertedIds()
,这是一个有效的调用。
目前,在世界其他地方避开了ES6语法:
var upserted = result.getUpsertedIds(); // get this from the bulk result
upserted = upserted.map(function(up) { return up._id }); // filter out just the _id values
var modifiedIds = edges.map(function(edge) { // get _id only from source
return edge.id;
}).filter(function(edge) {
return upserted.indexOf(edge) == -1; // and return only non upserted
});
from的返回结果.getUpsertedIds()
是一个对象数组,其中包含批量更新的“索引”位置和_id
“ upsert”的生成或提供的值。
[ { index: 0, _id: 1 } ]
因此,将您的输入列表与“ upserted”列表进行匹配,以查看“不存在的内容”,基本上会返回可能刚刚修改过的内容。当然要注意,如果值已经与修改相同,那么它实际上根本不是修改。
但是由于API的工作方式,这与您将要达到的目标非常接近。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句