Skip to content

Commit 899f52e

Browse files
committed
CSHARP-987: fixed issue with bulk upsert identifiers on pre-2.6 servers.
1 parent 88d1dfb commit 899f52e

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

MongoDB.Driver/Operations/BulkWriteBatchResult.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,28 @@ public static BulkWriteBatchResult Create(
258258
{
259259
var processedRequests = new[] { request };
260260
var unprocessedRequests = Enumerable.Empty<WriteRequest>();
261-
var upsertId = (writeConcernResult == null) ? null : writeConcernResult.Upserted;
261+
BsonValue upsertId = null;
262+
var documentsAffected = 0L;
263+
if(writeConcernResult != null)
264+
{
265+
documentsAffected = writeConcernResult.DocumentsAffected;
266+
upsertId = writeConcernResult.Upserted;
267+
var updateRequest = request as UpdateRequest;
268+
if (upsertId == null &&
269+
documentsAffected == 1 &&
270+
updateRequest != null &&
271+
updateRequest.IsUpsert.GetValueOrDefault(false) &&
272+
!writeConcernResult.UpdatedExisting)
273+
{
274+
// Get the _id field first from the Update document
275+
// and then from the Query document.
276+
upsertId = updateRequest.Update.ToBsonDocument()
277+
.GetValue(
278+
"_id",
279+
updateRequest.Query.ToBsonDocument()
280+
.GetValue("_id", null));
281+
}
282+
}
262283
var upserts = (upsertId == null) ? Enumerable.Empty<BulkWriteUpsert>() : new[] { new BulkWriteUpsert(0, upsertId) };
263284
var writeErrors = __noWriteErrors;
264285
WriteConcernError writeConcernError = null;
@@ -277,7 +298,6 @@ public static BulkWriteBatchResult Create(
277298
}
278299
}
279300

280-
var documentsAffected = (writeConcernResult == null) ? 0 : writeConcernResult.DocumentsAffected;
281301
if (request.RequestType == WriteRequestType.Insert && writeErrors.Count == 0)
282302
{
283303
documentsAffected = 1; // note: DocumentsAffected is 0 for inserts

MongoDB.DriverUnitTests/Operations/BulkWriteOperationTests.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,8 +1087,10 @@ public void TestUpsertWithMultipleMatchingDocuments(bool ordered)
10871087
public void TestUpsertWithNoMatchingDocument(bool ordered)
10881088
{
10891089
_collection.Drop();
1090-
var id1 = ObjectId.GenerateNewId();
1091-
var id2 = ObjectId.GenerateNewId();
1090+
1091+
// use non-ObjectIds to ensure functionality against < 2.6 servers
1092+
var id1 = 1;
1093+
var id2 = 2;
10921094
_collection.Insert(new BsonDocument { { "_id", id2 }, { "x", 2 } });
10931095

10941096
var bulk = InitializeBulkOperation(_collection, ordered);

0 commit comments

Comments
 (0)