Skip to content

Commit aa0adf0

Browse files
committed
Explicitly handle null values in the CommandResultArrayCodec
Allows null values to be handled when using distinct JAVA-2386
1 parent 8a3cbc9 commit aa0adf0

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

driver-core/src/main/com/mongodb/operation/CommandResultArrayCodec.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,12 @@ public BsonArray decode(final BsonReader reader, final DecoderContext decoderCon
4545

4646
List<T> list = new ArrayList<T>();
4747
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
48-
list.add(decoder.decode(reader, decoderContext));
48+
if (reader.getCurrentBsonType() == BsonType.NULL) {
49+
reader.readNull();
50+
list.add(null);
51+
} else {
52+
list.add(decoder.decode(reader, decoderContext));
53+
}
4954
}
5055
reader.readEndArray();
5156

driver/src/test/acceptance/com/mongodb/acceptancetest/core/CollectionAcceptanceTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,22 @@ public void shouldBeAbleToUseBsonValueToDistinctDocumentsOfVaryingTypes() {
310310
new BsonDocument("e", new BsonInt32(3))))))));
311311
}
312312

313+
@SuppressWarnings("unchecked")
314+
@Test
315+
public void shouldBeAbleToHandleNullValuesWhenUsingDistinct() {
316+
collection.drop();
317+
collection.insertMany(asList(new Document("id", "a"), new Document("id", "b"), new Document("id", null)));
318+
319+
List<String> distinctStrings = collection.distinct("id", String.class).into(new ArrayList<String>());
320+
assertTrue(distinctStrings.containsAll(asList("a", "b", null)));
321+
322+
collection.drop();
323+
collection.insertMany(asList(new Document("id", 1), new Document("id", 2), new Document("id", null)));
324+
325+
List<Integer> distinctInts = collection.distinct("id", Integer.class).into(new ArrayList<Integer>());
326+
assertTrue(distinctInts.containsAll(asList(1, 2, null)));
327+
}
328+
313329
private void initialiseCollectionWithDocuments(final int numberOfDocuments) {
314330
MongoCollection<Document> collection = database.getCollection(getCollectionName()).withWriteConcern(WriteConcern.ACKNOWLEDGED);
315331
for (int i = 0; i < numberOfDocuments; i++) {

0 commit comments

Comments
 (0)