@Override
    public void upgrade() {
        if (clusterConfigService.get(MigrationCompleted.class) != null) {
            LOG.debug("Migration already done.");
            return;
        }

        // Do not overwrite an existing default index config
        boolean defaultDone = clusterConfigService.get(DefaultIndexSetConfig.class) != null;
        final ImmutableSet.Builder<String> builder = ImmutableSet.builder();

        final FindIterable<Document> documents = collection.find(exists(FIELD_DEFAULT)).sort(ascending(FIELD_CREATION_DATE));

        for (final Document document : documents) {
            final ObjectId id = document.getObjectId(FIELD_ID);
            final String idString = id.toHexString();
            final boolean isDefault = firstNonNull(document.getBoolean(FIELD_DEFAULT), false);

            if (!defaultDone && isDefault) {
                defaultDone = true;
                clusterConfigService.write(DefaultIndexSetConfig.create(idString));
            }

            final long modifiedCount = collection.updateOne(eq(FIELD_ID, id), unset(FIELD_DEFAULT)).getMatchedCount();

            if (modifiedCount > 0) {
                LOG.info("Removed <default> field from index set <{}> ({})", document.getString(FIELD_TITLE), idString);
                builder.add(idString);
            } else {
                LOG.error("Couldn't remove <default> field from index set <{}> ({})", document.getString(FIELD_TITLE), idString);
            }
        }

        clusterConfigService.write(MigrationCompleted.create(builder.build()));
    }
@Test
    @MongoDBFixtures("V20161215163900_MoveIndexSetDefaultConfigTest.json")
    public void upgrade() throws Exception {
        final long count = collection.countDocuments();

        migration.upgrade();

        final MigrationCompleted migrationCompleted = clusterConfigService.get(MigrationCompleted.class);

        assertThat(collection.countDocuments())
                .withFailMessage("No document should be deleted by the migration!")
                .isEqualTo(count);
        assertThat(collection.countDocuments(Filters.exists("default")))
                .withFailMessage("The migration should have deleted the \"default\" field from the documents!")
                .isEqualTo(0L);

        assertThat(clusterConfigService.get(DefaultIndexSetConfig.class))
                .withFailMessage("The DefaultIndexSetConfig should have been written to cluster config!")
                .isNotNull();
        assertThat(clusterConfigService.get(DefaultIndexSetConfig.class).defaultIndexSetId()).isEqualTo("57f3d721a43c2d59cb750001");

        assertThat(migrationCompleted).isNotNull();
        assertThat(migrationCompleted.indexSetIds()).containsExactlyInAnyOrder("57f3d721a43c2d59cb750001", "57f3d721a43c2d59cb750003");
    }