问题
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