1

It has been well documented how to get a return Id from an Insert to a MongoDb collection in C# (Example). But how do I get that for an upserted document? Is there a way, short of querying for the Id again, to use the SafeModeResult returned by an Update to find the upserted document Id?

My code:
var query = abc;
var update = xyz;
try
{
   db["Collection"].Update(query, update, UpdateFlags.Upsert);
}
catch
{
}
Community
  • 1
  • 1
carlbenson
  • 3,177
  • 5
  • 35
  • 54

1 Answers1

0

Solution found:

db["Collection"].FindAndModify(query, SortBy.Ascending(), update, true, true).Response.GetValue(1).AsBsonDocument.GetValue("_id")

returns the ObjectId.

carlbenson
  • 3,177
  • 5
  • 35
  • 54
  • So you know, `FindAndModify` is an atomic function, which means that if you are doing a lot of writes, it could be slow as it will lock the whole database for each write. I don't *believe* mongo currently supports collection level locking, so if you run a lot of these, it may cause a slowdown. – Christopher Currens Oct 14 '11 at 18:51