Andrey Yaskulsky
Andrey Yaskulsky

Reputation: 2526

Transform each array object into a single value

I have a document of the following structure:

{
    "_id" : ObjectId("598446bb13c7141f1"),
    "trackerId" : "598446ba-fa9b-4000-8000-4ea290e",
    "powerMetrics" : [ 
        {
            "duration" : 0.15,
            "powerConsumption" : 0.1
        }, 
        {
            "duration" : 0.1,
            "powerConsumption" : 0.05
        }
    ]
}

My goal is to get another document, which would contain powerMetrics array that would consist of decimals computed in the following way: powerConsumption/duration so that as a result I would get:

{
     ....
    "powerMetrics" : [ 
        {
            0.6666
        }, 
        {
            0.5
        }
    ]
}

Size of powerMetrics can be dynamic and unknown.

I searched and could not find how can this be achieved and would appreciate any help, thanks!

Upvotes: 0

Views: 45

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path : "$powerMetrics",
                preserveNullAndEmptyArrays : true // optional
            }
        },

        // Stage 2
        {
            $group: {
            _id:'$_id',
            metrics:{$addToSet:{$divide:['$powerMetrics.powerConsumption','$powerMetrics.duration']}}
            }
        },

        // Stage 3
        {
            $project: {
             avgVal:{$avg:'$metrics'}
            }
        },

    ]



);

Upvotes: 1

s7vr
s7vr

Reputation: 75984

You can use $map to with $divide to output decimal values in 3.4 mongo version.

db.col_name.aggregate([
  {
    "$addFields": {
      "powerMetrics": {
        "$map": {
          "input":"$powerMetrics",
          "in": {"$divide":["$$this.powerConsumption","$$this.duration"]}
        }
      }
    }
  }
])

Upvotes: 3

Related Questions