diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java index 5d91a64d..5c530a60 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java @@ -427,25 +427,34 @@ private void dropIndexes(MongoCollection
collection, Document query) { Object index = query.get("index"); Assert.notNull(index, () -> "Index name must not be null"); MongoCollection
indexCollection = indexes.get(); + Document nsQuery = new Document("ns", collection.getFullName()); if (Objects.equals(index, "*")) { - for (Document indexDocument : indexCollection.queryAll()) { + for (Document indexDocument : indexCollection.handleQuery(nsQuery)) { Document indexKeys = (Document) indexDocument.get("key"); if (!isPrimaryKeyIndex(indexKeys)) { dropIndex(collection, indexDocument); } } - } else if (index instanceof String) { - dropIndex(collection, new Document("name", index)); } else { - Document indexKeys = (Document) index; - Document indexQuery = new Document("key", indexKeys).append("ns", collection.getFullName()); - Document indexToDrop = CollectionUtils.getSingleElement(indexCollection.handleQuery(indexQuery), - () -> new IndexNotFoundException(indexKeys)); + if (index instanceof String indexName) { + nsQuery.append("name", indexName); + } else { + nsQuery.append("key", (Document) index); + } + Document indexToDrop = CollectionUtils.getSingleElement(indexCollection.handleQuery(nsQuery), + () -> createIndexNotFoundException(index)); int numDeleted = dropIndex(collection, indexToDrop); Assert.equals(numDeleted, 1, () -> "Expected one deleted document"); } } + private static IndexNotFoundException createIndexNotFoundException(Object index) { + if (index instanceof String indexName) { + return new IndexNotFoundException("index not found with name [" + indexName + "]"); + } + return new IndexNotFoundException((Document) index); + } + private int dropIndex(MongoCollection
collection, Document indexDescription) {
String indexName = (String) indexDescription.get("name");
dropIndex(collection, indexName);
diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java
index 3bd4c9eb..eaa968b4 100755
--- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java
+++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractBackendTest.java
@@ -723,6 +723,82 @@ void testDropIndexes_twoIndexesWithTheSameKey() {
);
}
+ // https://github.com/bwaldvogel/mongo-java-server/issues/246
+ @Test
+ void testDropIndexes_string_twoIndexesWithTheSameKey() {
+ collection.insertOne(json("_id: 1, c: 10"));
+
+ MongoCollection