@@ -734,8 +734,9 @@ BulkWriteResult executeWriteCommandProtocol() {
734
734
@ Override
735
735
WriteResult executeWriteProtocol (final int i ) {
736
736
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 );
739
740
}
740
741
741
742
@ Override
@@ -759,8 +760,9 @@ BulkWriteResult executeWriteCommandProtocol() {
759
760
@ Override
760
761
WriteResult executeWriteProtocol (final int i ) {
761
762
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 );
764
766
}
765
767
766
768
@ Override
@@ -921,6 +923,26 @@ private DBObject getErrorResponseDetails(final DBObject response) {
921
923
}
922
924
return details ;
923
925
}
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
+ }
924
946
}
925
947
}
926
948
}
0 commit comments