0

I have collection in that collection 3 field. These field is in arrayIndex format. Collection sample as follows

    { 
        "_id" : ObjectId("576165f58d8b8f39458b456c"), 
        "EventTS" : ISODate("2016-06-07T03:30:00.000+0000"), 
        "PowerStatus" : [
           NumberInt(1), 
           NumberInt(1), 
           null, 
           NumberInt(1), 
           null
         ], 
        "TempStatus" : [
           NumberInt(1), 
           null, 
           NumberInt(1), 
           null, 
           null
        ], 
        "UPSStatus" : [
           NumberInt(1), 
           null, 
           NumberInt(1)
        ]
   }

This is my sample of collection one record. Basically PowerStatus, TempStatus, and UPSStatus is arrayindex format. In this field data stored 1 or null value only. Firstly i have to count 1 in individual filed after that I have to calculate the average of PowerStatus, TempStatus, and UPSStatus. And I try to get result in this format as shown below

  {
  "result": [
    {
      "PowerStatus": 77,
      "TempStatus": 12,
      "UPSStatus": 11
    }
  ]
}

When query excute after that i want output Like in collection average of PowerStatus is 77, TempStatus is 12 and UPSStatus is 11. Please suggest me how to calculate average of 3 filed?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sandip kakade
  • 1,346
  • 5
  • 23
  • 49

1 Answers1

0

You can use aggregation framework for that.

As we don't have your data set we cannot chek results - but see below proposed solution for ypur problem;

db.dhsari.aggregate([{
            $unwind : "$PowerStatus"
        }, {
            $unwind : "$TempStatus"
        }, {
            $unwind : "$UPSStatus"
        }, {
            $group : {
                _id : null,
                PowerStatus : {
                    $avg : "$PowerStatus"
                },
                TempStatus : {
                    $avg : "$TempStatus"
                },
                UPSStatus : {
                    $avg : "$UPSStatus"
                },
            }
        }, {
            $project : {
                _id : 0,
                result : [{
                        "PowerStatus" : "$PowerStatus",
                        "TempStatus" : "$TempStatus",
                        "UPSStatus" : "$UPSStatus"
                    }
                ]

            }
        }

    ])
profesor79
  • 9,213
  • 3
  • 31
  • 52