1

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"}
            }
        }
    ]
);
0

1 Answer 1

2

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"}
}}
]);
Sign up to request clarification or add additional context in comments.

4 Comments

sorry, _id are different , I just wanted to simplify
So like below ? db.collection.aggregate( [ { $unwind: { path: "$cpu", includeArrayIndex: "VS" } }, {$match: {"VS":{"$eq":1}}}, { $group: { _id: "hostname", avgCPU: {$avg: "$cpu"} } } ] );
I have update my answer with a query that will get the result that you need
Appreciate, print(JSON.stringify(db.cpu.aggregate(..)) gives me {"_firstBatch":[{"_id":0,"firstAvg":0,"lastAvg":0}],"_cursor":{}} ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.