繁体   English   中英

有没有办法通过使用 mongodb 聚合和投影来返回完全不同的数据结构?

[英]Is there a way to return a whole different data structure by using mongodb aggregations and projections?

假设我有以下 mongodb 集合,其结构如下:

mongodocument:
   _id: xxx
    A: "CLEYMAR_COMPANY"
    category: Object
        ENGINEER: Object
        ARQUITECT: Object

专业可以是 null 基于公司。

我想根据以下查询返回一个数据结构:

根据给定 A 的键列表的类别返回结果集,例如

["CLEYMAR_COMPANY", "VIC_COMPANY"] 

以及类别列表,例如

["ENGINEER", "ARQUITECT"]

结果:

ENGINEER_RESULT :  [ENGINEER(corresponding to CLEYMAR COMPANY)      ENGINEER(corresponding to VIC_COMPANY)]

 ARQUITECT_RESULT: [ARQUITECT(corresponding to VIC COMPANY)]. 
    
    

您需要自动装配 mongo 模板。

@Autowired
private MongoTemplate mongoTemplate;
  • $match以匹配公司
  • $addFields覆盖类别字段。 由于我们在类别中将动态键作为类别,因此我们将使用$objectToArray将其与键值对组成数组。 然后用职业列表过滤数组。 一旦我们过滤,它将给出数组。 为了使其成为原始形式,我们使用$arrayToObject

由于 spring 数据不提供任何$addFields ,我们需要使用TRICK 将 MONGO SHELL 查询转换为等效 ZC71E8D17D41C21DE620D260881D6

方法是

public List<Object> test(List<String> companies,List<String> professions ) {

    Aggregation aggregation = Aggregation.newAggregation(
        match(Criteria.where("A").in(companies)),
        a-> new Document("$addFields",
                new Document("category",
                        new Document("$arrayToObject",
                            new Document("$filter"
                                new Document()
                                .append("input",new Document("$objectToArray","$category"))                     
                                .append("cond",
                                    new Document("$in",Arrays.asList("$$this.k",professions))
                                )
                            )
                        )                                       
            )
        )

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}

工作蒙戈游乐场

注意:java 代码未经测试。 它是基于工作 mongo 查询编写的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM