System is having the below Document information in DB:
{
"systemName": "ABC",
"systemUsageAttrs" : [
{
"cpuUsage": 30,
"memUsage": 40,
"isActive": false
},
{
"cpuUsage": 88.2,
"memUsage": 33.5,
"isActive": false
},
{
"cpuUsage": 66.3,
"memUsage": 79.5,
"isActive": true
},
{
"cpuUsage": 80.5,
"memUsage": 63,
"isActive": true
}
]
}
I have tried the arregration using mongo java driver and below is the code snippet for:
List<Document> systemDetailsAL = sysUsageDetailsColl.aggregate(
asList(
match(eq("systemName","ABC")),
unwind("$systemUsageAttrs"),
match(eq("systemUsageAttrs.isAcive",true)),
group("$_id", Accumulators.push("systemName","$systemName"),
Accumulators.push("systemUsageAttrs", "$systemUsageAttrs")),
project(Projections.fields(Projections.excludeId(),
Projections.include("systemName", "systemUsageAttrs")))
)
).into(new ArrayList<Document>());
Above provides me the output in terms of ArrayList with two elements, 0th Element is with Document having key "systemName" and value is ArrayList with two elements. 1th position element is with Document having key 'systemUsageAttrs' and value is ArrayList with two elements i.e all system usage details.
Another thing is tried is commeting the group part is the above code, so it provides me a list of 2 Documents as
{
serverName: ABC,
systemUsageAttr: {
cpuUSage: xxx,
memUsage: yyy,
isActive:true
}}
and 2nd Document
{
serverName: ABC,
systemUsageAttr: {
cpuUSage: ttt,
memUsage: sss,
isActive:true
}}
Is it possible to return a a list with only 1 element using aggregation, such as it give below output
{
serverName: ABC,
systemUsageAttr: [
{
cpuUSage: xxx,
memUsage: yyy,
isActive:true
},
{
cpuUSage: ttt,
memUsage: sss,
isActive:true
}
}
Any help or pointers appreciated.