Mongodb只获取特定字段

时间:2012-09-11 21:15:25

标签: mongodb mongodb-java

我有两个收藏品

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}}

当我进行dbref fetch时,我会得到引用它的所有字段。

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

输出:

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

但是我只需要获取NAME字段如何限制它。我试过这样的。

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()); 
}

但是我在这一行中得到空指针异常

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

如何限制mongodb java中的字段?

1 个答案:

答案 0 :(得分:1)

我想也许您的错误出现在以下代码中:whereMap.put("tennat_id", 1);应该代之以tenant_id

除此之外,您的代码看起来还不错。

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

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