zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    JavaScript学习(二)
    javaScript学习(一)
    CSS学习(一)
    HTML学习(一)
    ES之node机器配置elasticsearch.yml
    ES之master机器配置elasticsearch.yml
    jenkins--前端依赖之 node
    jenkins--邮件插件配置
    JsonPath提取表达式
    this关键字的作用
  • 原文地址:https://www.cnblogs.com/liwei1994/p/11340828.html
Copyright © 2011-2022 走看看