0

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?

4

1 回答 1

1

我认为您的错误可能在此代码中:whereMap.put("tennat_id", 1);应该tenant_id改为。

除此之外,您的代码看起来还可以。

如果您不想获取 _id 字段,可以将另一个对象添加到您的field对象中_id:0。您必须明确排除该_id字段:

BasicDBObject field=new BasicDBObject("name",1)
  .append("_id": 0);
于 2012-09-11T21:39:15.240 回答