how to check if an document is updated or inserted in MongoDB

我们两清 提交于 2019-12-11 05:21:50

问题


I'm just wondering if there's way to check if a given document is updated or inserted in MongoDB after a upsert operation in Java:

DBCollection col = getCollection();
// either this
col.findAndModify(query, null, null, false, contact, false, true);
// or this
WriteResult wr = col.update(query, contact, true, false);

回答1:


Generally, WriteResult will hold information regarding whether it was successful or not; if successful, the document will be there.

You could also do a simple col.count(new BasicDBObject("_id",{id of your document})) and check if the value is 1.




回答2:


1-> step : set the profiler using > db.setProfilingLevel(2); on the document target.
2-> run this query

db.system.profile.find({},{ts:1, op:1, ns:1}).sort({ts: -1}).forEach(printjson);

it will show you in the op attribute if the given document is updated or inserted and ns is the document name. ts when the query run.



来源:https://stackoverflow.com/questions/12572696/how-to-check-if-an-document-is-updated-or-inserted-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!