Jessie
Jessie

Reputation: 1105

Mongodb fetching only particular field

I have two collections

checkone
  {"_id":1,"name":"alex"},
  {"_id":2,"name":"sandy"}

checktwo
  {"_id":11,"password":"alex",tenant_id:{$ref:"checkone","$id":1}}
  {"_id":12,"password":"suman",tenant_id:{$ref:"checkone","$id":2}}

when I do dbref fetch, am getting all the fields referencing it.

DBCursor cursor = coll.find();
while(cursor.hasNext()){
  DBRef addressObj = (DBRef)cursor.next().get("tenant_id");
  System.out.println(addressObj.fetch());   
}

Output:

{"_id":1,"name":"alex"},
{"_id":2,"name":"sandy"}

But I need to fetch only NAME field how to restrict it. I have tried it like this.

BasicDBObject query=new BasicDBObject();

Map<String, Object> whereMap = new HashMap<String, Object>();
whereMap.put("tennat_id", 1);
query.putAll(whereMap); 
BasicDBObject field=new BasicDBObject("name",1);
DBCursor cursor = coll.find(query,field);

while(cursor.hasNext()){
    DBRef addressObj = (DBRef)cursor.next().get("tenant_id");
     System.out.println(addressObj.fetch()); 
}

But I am getting null pointer exception in this line

DBCursor cursor = coll.find(query,field);

How to restrict the fields in mongodb java?

Upvotes: 0

Views: 1094

Answers (1)

Eve Freeman
Eve Freeman

Reputation: 33175

I think maybe your error is in this code: whereMap.put("tennat_id", 1); which should say tenant_id instead.

Aside from that, your code looks ok.

If you don't want to get the _id field, you can add another object to your field object for _id:0. You have to explicitly exclude the _id field:

BasicDBObject field=new BasicDBObject("name",1)
  .append("_id": 0);

Upvotes: 1

Related Questions