MongoDB JavaAPI实现聚合去重统计

依赖

<dependency>
     <groupId>org.mongodb</groupId>
     <artifactId>mongo-java-driver</artifactId>
     <version>3.4.2</version>
</dependency>

MongoDB在SpringBoot中的配置


@Component
public class MongoConfig {

    private String db;

    private MongoDatabase mongoDatabase;

    private MongoClient client;
    @Value("${mongodb.url}")
    private String mongoDbUrl;

    //刚启动程序的初始化
    @PostConstruct
    public boolean init() {
        try {
            MongoClientURI uri = new MongoClientURI(mongoDbUrl);
            this.db = uri.getDatabase();

            client = new MongoClient(uri);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return initDatabaseAndCollections();
    }

    public boolean initDatabaseAndCollections() {
        if (initDatabase()) {
            return true;
        }
        return false;
    }

    public MongoConfig() {
    }


    public boolean initDatabase() {
        ListDatabasesIterable<Document> iterable = client.listDatabases();
        Iterator<Document> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            Document document = iterator.next();
            String database = (String) document.get("name");
            if (database != null && database.equals(db)) {
                mongoDatabase = client.getDatabase(db);
                return true;
            }
        }

        return false;
    }

    public MongoCollection getCollection(String collectionName){
        return mongoDatabase.getCollection(collectionName);
    }

    public void close() {
        if (client != null) {
            client.close();
        }
    }
}

 

方法

@Repository
public class CustomerTreeDaoImpl implements ICustomerTreeDao {


    @Autowired
    private MongoConfig mongoConfig;
   

    @Override
    public List<StatisticDTO> statisticBy(final String group, final String fieldName) {
        if (StringUtils.isEmpty(group) || StringUtils.isEmpty(fieldName)) {
            return new ArrayList<>(0);
        }
        final MongoCollection<Document> collection = mongoConfig.getCollection(CUSTOMER_TREE_COLLECTION_NAME);
        //查询条件
        Bson condition = Filters.and(Filters.eq("group", group));
        List<StatisticDTO> statistic = new ArrayList<>();

        Block<Document> printBlock = new Block<Document>() {
            @Override
            public void apply(Document document) {
                //document中包括_id,如,通过省份分组的话_id就是省份名称或者是省份代码,根据库中具体的数据而定
                //包括分组中的fieldName,这个name中存的就是数值,如果北京有20条数据,那么fieldName对应的值就是20.
                final StatisticDTO statisticDTO = new StatisticDTO();
                statisticDTO.setKey(document.getString("_id"));
                statisticDTO.setValue(document.getLong(fieldName));
                statistic.add(statisticDTO);
            }
        };
        //执行聚合操作
        collection.aggregate(
                Arrays.asList(
                        //查询条件匹配
                        Aggregates.match(condition),
                        //分组,根据fieldName分组,“$”符号必须添加
                        Aggregates.group("$"+fieldName,
                                Accumulators.sum(fieldName, 1L))
                )
        ).forEach(printBlock);//此处的foreach会循环执行上面printBlock对象中的applay方法
        return statistic;
    }
}

最后

有缘人,希望这篇博客可以帮助你,点个👍吧

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值