(function() {
"use strict";
const dbName = "test";
const collName = "foo";
const ns = dbName + "." + collName;
const st = new ShardingTest({shards: 2, config: 1});
assert.commandWorked(st.s.adminCommand({enableSharding: dbName}));
st.ensurePrimaryShard(dbName, st.shard0.shardName);
assert.commandWorked(st.s.adminCommand({shardCollection: ns, key: {skey: 1}}));
assert.commandWorked(st.s.adminCommand({split: ns, middle: {skey: 0}}));
assert.commandWorked(
st.s.adminCommand({moveChunk: ns, find: {skey: 5}, to: st.shard1.shardName}));
const mongosColl = st.s.getDB(dbName)[collName];
assert.commandWorked(mongosColl.createIndex({skey: 1, uniqueField: 1}, {unique: true}));
assert.writeOK(mongosColl.insert({_id: 1, skey: -5, uniqueField: 0}));
const orphanColl = st.rs1.getPrimary().getDB(dbName)[collName];
assert.writeOK(orphanColl.insert({_id: 1, skey: -5, uniqueField: 0}));
assert.writeOK(orphanColl.insert({_id: 2, skey: -5, uniqueField: 1}));
const session = st.s.startSession();
session.startTransaction();
assert.commandFailedWithCode(session.getDatabase(dbName).runCommand({
update: collName,
updates: [{q: {uniqueField: 0}, u: {$set: {uniqueField: 1}}, multi: true}]
}),
ErrorCodes.DuplicateKey);
assert.sameMembers(mongosColl.find().toArray(), [{_id: 1, skey: -5, uniqueField: 0}]);
assert.commandWorkedIgnoringWriteErrors(mongosColl.getDB().runCommand({
update: collName,
updates: [{q: {uniqueField: 0}, u: {$set: {uniqueField: 1}}, multi: true}]
}));
assert.sameMembers(mongosColl.find().toArray(), [{_id: 1, skey: -5, uniqueField: 1}]);
st.stop();
})();