@@ -734,8 +734,9 @@ BulkWriteResult executeWriteCommandProtocol() {
734734 @ Override
735735 WriteResult executeWriteProtocol (final int i ) {
736736 ModifyRequest update = updateRequests .get (i );
737- return update (update .getQuery (), update .getUpdateDocument (), update .isUpsert (), update .isMulti (), writeConcern ,
738- encoder );
737+ WriteResult writeResult = update (update .getQuery (), update .getUpdateDocument (), update .isUpsert (),
738+ update .isMulti (), writeConcern , encoder );
739+ return addMissingUpserted (update , writeResult );
739740 }
740741
741742 @ Override
@@ -759,8 +760,9 @@ BulkWriteResult executeWriteCommandProtocol() {
759760 @ Override
760761 WriteResult executeWriteProtocol (final int i ) {
761762 ModifyRequest update = replaceRequests .get (i );
762- return update (update .getQuery (), update .getUpdateDocument (), update .isUpsert (), update .isMulti (), writeConcern ,
763- encoder );
763+ WriteResult writeResult = update (update .getQuery (), update .getUpdateDocument (), update .isUpsert (),
764+ update .isMulti (), writeConcern , encoder );
765+ return addMissingUpserted (update , writeResult );
764766 }
765767
766768 @ Override
@@ -921,6 +923,26 @@ private DBObject getErrorResponseDetails(final DBObject response) {
921923 }
922924 return details ;
923925 }
926+
927+ WriteResult addMissingUpserted (final ModifyRequest update , final WriteResult writeResult ) {
928+ // On pre 2.6 servers upserts with custom _id's would be not be reported so we check if _id
929+ // was in the update query or the find query then massage the writeResult.
930+ if (update .isUpsert () && writeConcern .callGetLastError () && !writeResult .isUpdateOfExisting ()
931+ && writeResult .getUpsertedId () == null ) {
932+ DBObject updateDocument = update .getUpdateDocument ();
933+ DBObject query = update .getQuery ();
934+ if (updateDocument .containsField ("_id" )) {
935+ CommandResult commandResult = writeResult .getLastError ();
936+ commandResult .put ("upserted" , updateDocument .get ("_id" ));
937+ return new WriteResult (commandResult , writeResult .getLastConcern ());
938+ } else if (query .containsField ("_id" )) {
939+ CommandResult commandResult = writeResult .getLastError ();
940+ commandResult .put ("upserted" , query .get ("_id" ));
941+ return new WriteResult (commandResult , writeResult .getLastConcern ());
942+ }
943+ }
944+ return writeResult ;
945+ }
924946 }
925947 }
926948}
0 commit comments