少なくともシェルでは、ドキュメントが変更されたかどうかを区別できます (「参考文献」を参照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は、レコードが更新された後に実行されるコールバックです。2 つのパラメーターがあり、1 つ目はエラー オブジェクト (エラーが発生した場合)、2 つ目は変更されたレコードの数です。
別のアップデート
少なくともバージョン 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();
});