Jessie
Jessie

Reputation: 1105

mongodb - Sub document id value

I have a collection.

look
 { "_id" : 13.0 , "tenantref" : { "$id" : 3.0}}

I need to retrieve the value of id 3.0 using java. I am getting null pointer exception.

    BasicDBObject field = new BasicDBObject();
    BasicDBObject field = new BasicDBObject();
    field.put("tenantref.$id", 1);

    DBCursor cursor = mongo.getDB("number").getCollection("testthree").find(query,field);   

    while (cursor.hasNext()) 
    {       
    System.out.println(cursor.next().get("tenantref.$id"));
    }

I am getting null pointer exception. How do I need to get the value?

Upvotes: 0

Views: 640

Answers (1)

Philipp
Philipp

Reputation: 69663

cursor.next().get("tenantref.$id"));

The get() function of BasicDBObject does not support the dot syntax. You have to traverse the object hierarchy by hand. Try

((DBObject)cursor.next().get("tenantref")).get("$id");

Upvotes: 1

Related Questions