RLD RLD - 16 days ago 5
Java Question

Retrieving 'int' field from MongoDB Document throws NullPointerException

I know MongoDB field name is case sensitive, at least while retrieving a value for the field. I have following Java Program.

public class SimpleDocument {
public static void main(String[] args) {
Document doc = new Document("String","Aeroplane").append("int", 20);

String s1 = doc.getString("String");
String s2 = doc.getString("string");
System.out.println("s1="+s1+" and s2="+s2);

int i1 = doc.getInteger("int");
int i2 = doc.getInteger("Int"); //throws NullPointerException
System.out.println("i1="+i1+" and i2="+i2);
}
}


The first Sysout displays output as expected i.e., s1="Aeroplane" and s2=null. But the 2nd Sysout does not display anything as the line just above it throws a NullPointerException which I can't understand.

Can anybody explain the logic?

Answer
Document doc = new Document("String","Aeroplane").append("int", 20);

String s1 = doc.getString("String");
String s2 = doc.getString("string");
System.out.println("s1="+s1+" and s2="+s2);

int i1 = doc.getInteger("int");
int i2 = doc.getInteger("Int"); //throws NullPointerException
System.out.println("i1="+i1+" and i2="+i2);

For s1 you are reading in "String" which is equal to "Aeroplane".

  • s1="Aeroplane";

For s2 you are reading in "string" which will equal to null (doesn't exist in your document). Strings are objects and are NOT primitive data types, so they are able to store null inside of them.

  • s2=null;

For i1 you are reading in "int" which is equal to 20

  • i1=20;

For i2 you are reading in "Int" which will equal to null (doesn't exist in your document). Then you are trying to store null inside of a int primitive. So you will have an exception.

What you need to do is:

Integer i2 = doc.getInteger("Int");

This will prevent the exception from being thrown, and will allow i2=null;

Comments