今天需要做一個篩選程序,因為數據放在mongodb中,沒寫過分組的查詢語句,查了一些資料,終於寫出來了,分享給各位小伙伴
需求是 查詢 學員 在2019-07-29之后未同步的數據(同一個學員需要2條數據或以上才符合同步條件)
這是mongoDB原生語句

db.getCollection("ClassRecordOneDetail").aggregate([ //下面相當於sql 里面的 where synState = 0 and starttime >=to_date('2019-08-02','yyyy-MM-dd') {$match:{synState:0,"starttime":{$gte:new Date("2019-08-02")}}}, //下面相當於sql 里面的group by分組 分組字段為 stunum,starttime去掉了時分秒分組 {$group:{_id:{stunum : "$stunum" , starttime: { month: { $month: "$starttime" }, day: { $dayOfMonth: "$starttime" }, year: { $year: "$starttime"} }},counter:{$sum:1}}}, //下面相當於sql 里面的 having count(1) >1 {$match:{counter:{$gt:1}}} ]);
這是java代碼

import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoCollection; import org.bson.Document; import com.mongodb.client.MongoCursor; /** *這里我就寫出了mongoDB我使用的類,其他的導入類型我沒寫。 * **/ MongoCollection<Document> mc = MongoDBUtil.instance.getCollection("dzwl", "ClassRecordOneDetail"); Document sub_match = new Document(); sub_match.put("subState", 0); sub_match.put("starttime", new Document("$gte", date)); Document sub_group = new Document(); sub_group.put("_id", new Document("stunum","$stunum").append( "starttime", new Document("month",new Document("$month","$starttime")).append("day",new Document("$dayOfMonth","$starttime")).append("year",new Document("$year","$starttime")) )); sub_group.put("counter", new Document("$sum", 1)); Document match = new Document("$match", sub_match); Document group = new Document("$group", sub_group); Document match2 = new Document("$match", new Document("counter",new Document("$gt", 1))); List<Document> documents = new ArrayList<>(); documents.add(match); documents.add(group); documents.add(match2); MongoCursor<Document> cursor = mc.aggregate(documents).iterator(); //下面直接遍歷查詢查來的數據就可以了 MongoCursor<Document> cursor = mc.aggregate(documents).iterator(); try { while(cursor.hasNext()){ } } catch (Exception e) { // TODO: handle exception }