2015년 1월 2일 금요일

Is it possible to know whether a update query modified collection or not

is there a way to find whether a given 'update' query modified collection or not?



What version of MongoDB and what driver are you using? In 2.6 and with the latest versions of drivers, update operations should give you a way to see how many documents were modified. For example, in the MongoDB shell, update will return a WriteResult containing this information:

> db.test.drop()

> db.test.insert([{ "t" : 0, "x" : 1 }, { "t" : 0, "x" : 2 }, { "t" : 0, "x" : 3 }])
> db.test.update({ "t" : 0 }, { "$inc" : { "x" : 1 } }, { "multi" : true })
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

nModified won't count documents if the update was effectively a noop:

> db.test.update({ "t" : 0 }, { "$inc" : { "x" : 0 } }, { "multi" : true })
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 0 })

> db.test.find({}. { "_id" : 0 })
{ "t" : 0, "x" : 2 }
{ "t" : 0, "x" : 3 }
{ "t" : 0, "x" : 4 }
> db.test.update({ "t" : 0 }, { "$set" : { "x" : 2 } }, { "multi" : true })
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 2 })


댓글 없음:

댓글 쓰기