@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 upgradeWhenMigrationCompleted() throws Exception {
        // Count how many documents with a "default" field are in the database.
        final long count = collection.countDocuments(Filters.exists("default"));

        assertThat(count)
                .withFailMessage("There should be at least one document with a \"default\" field in the database")
                .isGreaterThan(0L);

        clusterConfigService.write(MigrationCompleted.create(Collections.emptySet()));
        migration.upgrade();

        // If the MigrationCompleted object has been written to the cluster config, the migration shouldn't do anything
        // and shouldn't touch the database. Thank means we should still have all documents with the "default" field
        // from the seed file in the database.
        assertThat(collection.countDocuments(Filters.exists("default"))).isEqualTo(count);
    }