From 7449324635c686aa631faa35a08d18c030b03c3d Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Mon, 10 Jun 2019 09:58:22 +0200 Subject: [PATCH] Fix distinct queries on fields with array values #70 --- .../mongo/backend/AbstractMongoCollection.java | 6 +++++- .../mongo/backend/AbstractBackendTest.java | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java index f42e277c4..a6223d478 100755 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java @@ -345,7 +345,11 @@ public synchronized Document handleDistinct(Document query) { for (Document document : queryDocuments(filter, null, 0, 0)) { Object value = Utils.getSubdocumentValue(document, key); if (!(value instanceof Missing)) { - values.add(value); + if (value instanceof Collection) { + values.addAll((Collection) value); + } else { + values.add(value); + } } } 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 34be88814..5733601fe 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 @@ -478,6 +478,18 @@ public void testDistinctUuids() throws Exception { ); } + // https://github.com/bwaldvogel/mongo-java-server/issues/70 + @Test + public void testDistinctArrayField() throws Exception { + collection.insertOne(json("_id: 1, n: null")); + collection.insertOne(json("_id: 2").append("n", Arrays.asList(1, 2, 3))); + collection.insertOne(json("_id: 3").append("n", Arrays.asList(3, 4, 5))); + collection.insertOne(json("_id: 4").append("n", 6)); + + assertThat(toArray(collection.distinct("n", Integer.class))) + .containsExactly(null, 1, 2, 3, 4, 5, 6); + } + @Test public void testInsertQueryAndSortBinaryTypes() throws Exception { byte[] highBytes = new byte[16];