java实现MongoDB中unwind与match用法

本文介绍如何使用MongoDB的unwind、match和sort操作,对嵌套文档中的数组进行拆分并按顺序排序,以实现数据处理和分析。实例演示了从复杂结构数据中提取并整理配置信息的过程。
摘要由CSDN通过智能技术生成

unwind:(拆分)将数组中的每一个值拆分为单独的文档。

match:(筛选)用于对文档集合进行筛选,然后可以对筛选所得到的文档子集上做聚合

sort:(排序)根据任何字段进行排序,与在普通查询中的语法相同。

示例如下:

目标:对嵌套文档中数组进行拆分,并正序排序

如:

数据的结构为:

直接查询到的数据:

想要拆分为下图效果:

 代码实现如下:

//  拆分数据(抽取方法)
    public JSONArray queryDocument(String productKey) {

        BasicDBObject query = new BasicDBObject();
        query.put("productKey", productKey);
        //拆分configContent
        ArrayList<Document> documents = Lists.newArrayList();
        Document match = new Document();
        match.put("$match", query);

        Document unwind = new Document().append("$unwind", new Document()
                .append("path", "$configModel")
                .append("includeArrayIndex", "arrayIndex")
                .append("preserveNullAndEmptyArrays", false));
        Document sort = new Document().append("$sort",new Document().append("arrayIndex",-1.0));
        documents.add(unwind);
        documents.add(match);
        documents.add(sort);
        
        AggregateIterable<Document> tslPart = mongoTemplate.getCollection(PROJECT_COLLECTION_NAME_FILE).aggregate(documents);
        //遍历得到document
        for (Document document : tslPart) {
            jsonArray.add(JSONUtil.parseObj(document.get("configModel")));
        }
        return jsonArray;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值