How to get _id after updating a MongoDB document? How to get _id after updating a MongoDB document? mongodb mongodb

How to get _id after updating a MongoDB document?


As far I know ReplaceOneAsync method doesn't return the UpsertedId when the document is replaced, you will see that field with a value when the document is inserted. If you replace an existing document, you can check in your DB that the replacement document is going to have the same _id of the old document:

var collection = GetMongoDatabase().GetCollection<BsonDocument>("foos");var d=collection.Find<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "bar")).FirstOrDefault();var id = d["_id"].ToString();//Check your id herevar document = new BsonDocument{     {"foo", "new bar"}};var result = await collection.ReplaceOneAsync(             Builders<BsonDocument>.Filter.Eq("foo", "bar"),             document,             new UpdateOptions {IsUpsert = true});var d1=collection.Find<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "new bar")).FirstOrDefault();var id1 = d1["_id"].ToString(); // You will see the same _id

Probably the method you are looking for is FindOneAndReplaceAsync:

var d =collection.FindOneAndReplace<BsonDocument>(Builders<BsonDocument>.Filter.Eq("foo", "new bar"),                                                   document,                                                  new FindOneAndReplaceOptions<BsonDocument, BsonDocument>()                                                   { IsUpsert=true,                                                    ReturnDocument=ReturnDocument.After                                                  });var id = d["_id"].ToString();