0
votes

I have the collection with document structure like this:

{
"_id" : "Host CPU Utilization (%)",
"count" : 1,
"avg" : NumberDecimal("20.2397439956"),
"flaga" : 4
},
{
"_id" : "Active Sessions Using CPU",
"count" : 1,
"avg" : NumberDecimal("4.0580000000"),
"flaga" : 4
},
 {
"_id" : "Wait Time (%)",
"count" : 1,
"avg" : NumberDecimal("1795.2150000000"),
"flaga" : 999
}

Is that possible to use pymongo changing data like:

{
"_id" : 4,
"Host CPU Utilization (%)" : NumberDecimal("20.2397439956"),
"Active Sessions Using CPU" : NumberDecimal("4.0580000000")
},
{
"_id" : 999,
"Wait Time (%)" : NumberDecimal("1795.2150000000"),
}

I have tried to use update commend rename but can't do it dynamically and can't combine two documents into one. If I use aggregation framework, I don't know how to $put documents with variable field name.

1

1 Answers

0
votes

Since version 3.4 we have $arrayToObject operator which might be helpful. You can try grouping by flaga field and then using mentioned operator.

db.myCollection.aggregate([
    { 
        $group: {
            "_id": "$flaga",
            "values": {
                "$push": {
                    "k": "$_id",
                    "v": "$avg"
                }
            }
        } 
    },
    {
        $project: {
            "_id": 1,
            "values": { $arrayToObject: "$values" }
        }
    }
])

This will give you results like:

{
   "_id":4,
   "values":{
      "Host CPU Utilization (%)":NumberDecimal("20.2397439956"),
      "Active Sessions Using CPU":NumberDecimal("4.0580000000")
   }
}

You can add next pipeline stage with $replaceRoot to get rid of this nesting but unfortunately you'll loose _id field and I bet it's not what you're looking for, so probably you should perform this post-processing in your business logic code.