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

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

根据公司的不同,职业可以为空。

我想return一个基于以下查询的数据结构:

Return 基于给定 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 TO CONVERT MONGO SHELL QUERY INTO EQUIVALENT JAVA OBJECTS

方法是

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();

}

工作Mongo playground

注意:java 代码未经测试。它是根据工作 mongo 查询

编写的