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

1、Document结构

统计mongodb数组类型的,某一个字段出现次数_第1张图片

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

  String datasetId = "NREUA4B4CVEHJIV6LMBXOV5BLA";

        List 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 cursor =  mdcMongoTemplate.getCollection("cdr_data").aggregate(aggregateList).iterator();
        while (cursor.hasNext()) {
            org.bson.Document doc = cursor.next();
            System.out.println(doc);
        }

 

你可能感兴趣的:(MongoDB学习笔记)