问题
I have collection of documents in mongodb 2.6.11 where 'cpu' is array showing [cpu0,cpu1], see example below
{ cpu: [ '100','20' ], hostname: 'host1',_id: 1 },
{ cpu: [ '40','30' ], hostname: 'host1',_id: 2 }, etc
I'm looking for average cpu on 'host1' which is ['70','25'] ( because '100'+'40'/2='70' and '20'+'30'='25' ). I am trying aggregate for cpu1 but it is not giving me right result
db.collection.aggregate(
[
{
$group:
{
_id:"hostname",
avgCPU: {$avg: "$cpu.1"}
}
}
]
);
回答1:
In MongoDB 2.6 positional notation in aggregation is unsupported, you will need to $unwind
your document, and on the next stage perform the $avg
.
In MondoDB 3.2 however, you have the $arrayElemAt operator which return the element at specified index { $arrayElemAt: [ <array>, <idx> ] }
Based on the document structure you posted, this query will do the work:
db.cpu.aggregate([
{$unwind: "$cpu"},
{$group: {
_id: "$_id",
first: {$first: "$cpu"},
last: {$last: "$cpu"}
}},
{$group: {
_id: 0,
firstAvg: {$avg: "$first"},
lastAvg: {$avg: "$last"}
}}
]);
来源:https://stackoverflow.com/questions/35226104/mongodb-aggregate-average-of-array-elements