標籤:dao層 i++ mongo pat 條件 from collect 模板 欄位
上文把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));
java操作mongodb