至少在 shell 中,您可以区分文档是否被修改(请参阅 参考资料nModified
)。
> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
节点更新
使用时,collection.update(criteria, update[[, options], callback]);
您可以检索已修改的记录数。
从节点文档
callback是记录更新后要运行的回调。有两个参数,第一个是错误对象(如果发生错误),第二个是被修改的记录数。
另一个更新
至少在 1.4.3 版本中,本机 Mongo Node 驱动程序的行为似乎与记录不符。可以使用批量 API(在 Mongo 2.6 中引入)来解决:
var col = db.collection('test');
// Initialize the Ordered Batch
var batch = col.initializeOrderedBulkOp();
batch.find({a: 2}).upsert().updateOne({"$addToSet": {"tags": "newTag"}});
// Execute the operations
batch.execute(function(err, result) {
if (err) throw err;
console.log("nUpserted: ", result.nUpserted);
console.log("nInserted: ", result.nInserted);
console.log("nModified: ", result.nModified); // <- will tell if a value was added or not
db.close();
});