上文把mongodb集成到spring,并将mongodb模板注入到dao层。
那么下面我们进行一些操作。
optionmongo.java 。
DB db=null; DBCollection coll=null; db=mongoTemplate.getDb(); coll= db.getCollection("test"); //全量查找,显示name,age,隐藏id属性。类似于select name,age from stu. DBCursor cur = coll.find(new BasicDBObject(),new BasicDBObject("name",1).append("id", 0).append("age", 1)).limit(500); while (cur.hasNext()) { DBObject object = cur.next(); System.out.println(object.get("name")); } //指定条件查找。 DBObject dbo = new BasicDBObject(); dbo.put("id", 110); DBCursor cur = coll.find(dbo,new BasicDBObject("name",1).append("id", 0).append("age", 1)).limit(500); while (cur.hasNext()) { DBObject object = cur.next(); System.out.println(object.get("name")); } //对查询结果进行字段显示更改。 while (cur.hasNext()) { DBObject object = cur.next(); DBObject newdbo=new BasicDBObject(); newdbo.put("姓名",object.get("name")) System.out.println(newdbo.get("姓名")); } //去重查询 BasicDBList ages = new BasicDBList(); //字段为集合,要求条件在集合里 //将条件加入集合 ages.add(age); //设置条件类 age字段集合里 有对应的条件。 tjdbo.put("age", new BasicDBObject("$in",ages)); //name去重显示 List bws=coll.distinct("name",tjdbo); for (int i = 0; i < bws.size(); i++) { DBObject dbo=new BasicDBObject(); dbo.put("name",bws.get(i)) ; System.out.println(dbo.get("name")); } //模糊查找 //定义一个匹配规则 Pattern pattern = Pattern.compile("^.*" + key +".*$", Pattern.CASE_INSENSITIVE); //定义条件类 DBObject dbo = new BasicDBObject(); dbo.put("name", pattern); cur = coll.find(dbo,new BasicDBObject("name",1).append("id", 0).append("age", 1));