Mongo-java-driver NullPointerException in getList

When using the mango-java driver: 3.12.1 getting NullPointerException exceptions when reading a collection containing null item from a document,

private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
    List<?> value = get(key, List.class);
    if (value == null) {
        return defaultValue;

    for (Object item : value) {
        if (!clazz.isAssignableFrom(item.getClass())) { //NullPointerException if document contain list with null item
            throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
    return (List<T>) value;

how we can add small fix

if (item!=null && !clazz.isAssignableFrom(item.getClass()))

Hi @Vi_Os, welcome!

Could you provide the following information to further clarify the question:

  • A minimal reproducible example code
  • An example document schema to show the null item field
  • Error stack trace to indicate where it’s throwing the NullPointerException


Hi @wan
In our schema we can`t check value in collection because multiple service can update it
in our workflow we can change model but i think in mongo-java-driver check for NULL before check type is better solution

You can reproduce NPE with this code,

 Document npe = new Document();
        List<Integer> numbers = Arrays.asList(1, null);
        npe.put("numbers", numbers);
        List<Integer> read = npe.getList("numbers", Integer.class);


Exception in thread "main" java.lang.NullPointerException
	at org.bson.Document.constructValuesList(
	at org.bson.Document.getList(
	at MainApplication.main(

This will not throw NullPointerException:

List<Integer> read = (List<Integer>) npe.get("numbers");
System.out.println(read);     // prints [1, null]

Yes, we use Get method but there unchecked cast and no type control.
It no good solution because exist method getList, with small bug)