数据库脚本:
db.status.save({"name":"xph"}); db.status.save({"name":"jzm", "age":"1000"}); db.status.save({"name":"hjt", "age":"6","count":"china"}); db.status.find({"name":"xph"}, {"name":true, "age":true});
java代码:
@Test public void test() { BasicDBObject condition = new BasicDBObject(); // condition.append("name", "xph"); BasicDBObject keys = new BasicDBObject(); keys.put("_id", 0); keys.put("name", 1); keys.put("age", 1); DBCursor cursor = dao.getMongoTemplate().getCollection("status").find(condition, keys).addOption(Bytes.QUERYOPTION_NOTIMEOUT); Iterator<DBObject> iterator = cursor.iterator(); while (iterator.hasNext()) { DBObject dbObject = iterator.next(); for(String key : dbObject.keySet()) { System.out.println(key + " >>>>>>>>>>>>>>>>>> " + dbObject.get(key)); } System.out.println(" .............................................................. "); } }
也就是能拿到MongoTemplate对象即可。