mongoDB 分組並對分組結果篩選類似於SQL中的(group by xxx having ) 附帶Java代碼


今天需要做一個篩選程序,因為數據放在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}}}
]);
View Code

 

這是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
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM