欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计mongodb数组类型的,某一个字段出现次数

程序员文章站 2022-04-15 14:45:09
...

1、Document结构

统计mongodb数组类型的,某一个字段出现次数

2、需求:统计data数组中,每个key出现的次数

  String datasetId = "NREUA4B4CVEHJIV6LMBXOV5BLA";

        List<BasicDBObject> aggregateList = new ArrayList<>();

        BasicDBObject matchCond = new BasicDBObject("$match", new BasicDBObject("dataset_id", datasetId));

        aggregateList.add(matchCond);
        aggregateList.add(new BasicDBObject("$unwind", "$data"));

        BasicDBObject groupCond = new BasicDBObject("$group", new BasicDBObject("_id", "$data.key").append("count" , new BasicDBObject("$sum", 1)));
        aggregateList.add(groupCond);

        //排序,同一字段出现次数前10的
        aggregateList.add(new BasicDBObject("$sort", new BasicDBObject("count", -1)));
        aggregateList.add(new BasicDBObject("$limit", 10));

        MongoCursor<org.bson.Document> cursor =  mdcMongoTemplate.getCollection("cdr_data").aggregate(aggregateList).iterator();
        while (cursor.hasNext()) {
            org.bson.Document doc = cursor.next();
            System.out.println(doc);
        }

 

相关标签: MongoDB学习笔记