Please help: Retrieving the value of an int inside an object inside a document

I’m pretty new to mongoDB, and I’m trying to retrieve an integer from my database.
Whenever I run my code, I receive a null pointer exception

Please assume ID = “533363285257355265” and that itemName.toUpperCase() = “CHEST”
Below is my code from my IDE:

MongoCollection members = Database.getCollection(“members”);
Document member = members.find(eq(“memberId”, memberID)).first();
int items = 0;
switch (itemType) {
case PERKS:
items = member.getInteger(“items.” + itemName.toUpperCase());
case CHESTS:
items = member.getInteger(“items.” + itemName.toUpperCase() + “_CHEST”);

Next, is the mongoDB compass… The document in question should be the one shown below, I don’t know why it gets a null pointer exception though.

One thing that catches my eye is that the memberId string in Compass has trailing spaces (at least x 2)

Not sure if your switch() statement will work. Typically, you reference the value of a sub-document using the dot notation:

PS: if you’re new to MongoDB, suggest that you take both the M001 Basics and M121 Aggregation Framework courses beforehand.


then the expression

will provide the string CHEST_CHEST not BASIC_CHEST.

That was an oopsie on my side, it is supposed to be BASIC

I would use my IDE or some print statement to make sure the intermediary values are what you think they are.

If Database is the correct database and that your collection is named members and that you only have one document with this memberId and that itemType equals CHESTS and that itemName.toUpperCase() equals BASIC then I see no reason why you would not get 25.

Since you get a null exception your IDE probably indicates the line number. I suspect that either Database is null or member is null. Probably you find does return null.

The issue is w/ me being new, is that I do not know how to tell if my thing is even pointing to the database properly

New to Java or new to MongoDB or both? M220J is for Java programmers so a basic knowledge of Java is prerequisite. If new to MongoDB, M001 should be taken first. A couple of print statements using System.err.println() will help you to output the value of your variables.

1 Like