juanp_1982
juanp_1982

Reputation: 1007

How to use $avg to average for a field inside of an array

I'm using Mongodb 3.2 and I need to calculate of all fields inside arrays

these is an example of my collection

{
  "memTotal" : 33730525659,
  "swapTotal" : 16936129790,
  "queueList" : [
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
  ],
},
{
  "memTotal" : 33730525659,
  "swapTotal" : 16936129790,
  "queueList" : [
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
  ],
},
{
  "memTotal" : 33730525659,
  "swapTotal" : 16936129790,
  "queueList" : [
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
    {
      "usedSlots" : 2,
      "totalSlots" : 8,
      "reservedSlots" : 0,
    },
  ],
},

I need to calculate average for "queueList.useSlots", "queueList.totalSlots", "queueList.totalSlots", please keep in mind that queueList is an array.

So far what I have done is use aggregation, first I {$unwind: "queueList"}, {$group:{useSlots:{$avg:"queueList.useSlots"}}}

but this return the wrong average :-(

any help would be very appreciated :-) thanks!

Upvotes: 1

Views: 3352

Answers (1)

notionquest
notionquest

Reputation: 39206

Please try the below query.

db.memory.aggregate([
{$unwind : "$queueList"}, 
{$group : {_id : "$_id",
   "avgUseSlots" :{$avg :  "$queueList.usedSlots"},
   "avgTotSlots" :{$avg :  "$queueList.totalSlots"},
   "avgReservedSlots" :{$avg :  "$queueList.reservedSlots"}
   }
   }
 ]);

Output:-

{
    "_id" : ObjectId("57816e7285ae6441865d83e4"),
    "avgUseSlots" : 2,
    "avgTotSlots" : 8,
    "avgReservedSlots" : 0
}

Upvotes: 3

Related Questions