我的收藏集具有如下文档结构:
{ 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获取AppVersion。例如:
基于所有AppTech为“ Java”的AppEnv的AppVersion(带有一些标志)。结果可能如下所示:
{
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'
}
有人可以建议我如何开始为此编写查询吗?
答案 0 :(得分:0)
您可以尝试这个
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']
}
}
答案 1 :(得分:0)
您可以使用MongoTemplate。
假设您的课程是这样的:
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
);