mongodbmongodb-queryspring-mongodbspring-mongo

Mongo aggregrate conditional $match, $group and $project


My collection has document structure like below:

{ 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'

}

I need to get AppVersion based on AppName/AppEnv/AppTech provided.For eg:

AppVersion(with some flag) based on AppEnv of all whose AppTech is 'Java'. The result could look like below:

{
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'

}

Can someone please suggest me how do i start writing queries for this?


Solution

  • You can try this one

    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' }
        }
    }
    

    ])

    I change the format of the output because the format that you expect is not possible. And i didn't include the hasVersionDiff field, you can just add it later.

     {
        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']
        }
    }