Mongo 汇总条件 $match、$group 和 $project

Mongo aggregrate conditional $match, $group and $project

我的 collection 的文档结构如下:

{ AppName: 'test',
AppEnv: 'Development'
AppTech:'Java'
AppVersion: '1_0',

AppName: 'test',
AppEnv: 'SQA'
AppTech:'Java'
AppVersion: '1_0',

AppName: 'test22',
AppEnv: 'Development'
AppTech:'Java'
AppVersion: '1_2',

AppName: 'test22',
AppEnv: 'SQA'
AppTech:'Java'
AppVersion: '1_1',

AppName: 'test22',
AppEnv: 'Production'
AppTech:'Java'
AppVersion: '1_0',

AppName: 'test2',
AppEnv: 'Development'
AppTech:'.NET'
AppVersion: '1_0'

}

我需要根据 AppName/AppEnv/AppTech provided.For 获取 AppVersion 例如:

AppVersion(带有一些标志)基于所有 AppTech 为 'Java' 的 AppEnv。结果可能如下所示:

{
AppName: 'test', 
AppTech: 'Java',
VersionInfo: [AppEnv: {'Development','SQA'}, AppVersion: {'1_0','1_1'}],
hasVersionDiff: 'false',

AppName: 'test22', 
AppTech: 'Java',
VersionInfo: [AppEnv: {'Development','SQA','Production}, AppVersion: {'1_2','1_1','1_0'}],
hasVersionDiff: 'true'

}

有人可以建议我如何开始为此编写查询吗?

你可以试试这个

let query = {AppTech: 'Java'};
let result = await Collection.aggregate([
{ $match: query },
{ $group: { 
    _id: '$AppName', 
    AppTech: {$first: '$AppTech' },
    AppEnv: {$push: '$AppEnv'},
     AppVersion: {$push: '$AppVersion'}} 
},
{
    $project: {
        AppName: '$_id',
        AppTech: '$AppTech',
        VersionInfo: { AppEnv: '$AppEnv', AppVersion: '$AppVersion' }
    }
}

])

我更改了输出格式,因为您期望的格式不可能。 而且我没有包含 hasVersionDiff 字段,您可以稍后添加它。

 {
    AppName: 'test', 
    AppTech: 'Java',
    VersionInfo: {
        AppEnv: ['Development','SQA'], 
        AppVersion: ['1_0','1_1']
    },
},
{
    AppName: 'test22', 
    AppTech: 'Java',
    VersionInfo: {
        AppEnv: ['Development','SQA','Production'],
        AppVersion: ['1_2','1_1','1_0']
    }
}

你可以使用 MongoTemplate。

假设您的 class 是这样的:

public class OutPutClass {
    String appName;
    String appTech;
    VersionInfo versionInfo;

    public class VersionInfo{

        List<String> appEnvs;
        List<String> appVersions;
    }
}

和 mongoTemplate 查询:

final Criteria criteria =
            Criteria.where("appTech").is("Java");
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("AppName")
                    .first("AppName")
                    .as("appName")
                    .first("AppTech")
                    .as("appTech")
                    .push("AppEnv").as("versionInfo.appEnvs")
                    .push("AppVersion").as("versionInfo.appVersions")
    );

mongoTemplate.aggregate(
                        aggregation,
                        DocumentClass.class,
                        OutputClass.class
                );