Kapil Khandelwal
Kapil Khandelwal

Reputation: 1176

MongoDB Convert this to key-value pairs

The output of my mongo query after applying groupyby is as follows:

[
  {
    "_id": "FAIL",
    "count": 2
  },
  {
    "_id": "PASS",
    "count": 3
  }
]

How can I convert this to key value pairs like this:

[
  metric_count:{      
  "FAIL":2,
  "PASS":3,
  "TOTAL":5   //sum of pass count and fail count
 }
]

MongoDB Playground

Upvotes: 0

Views: 461

Answers (1)

greenlikeorange
greenlikeorange

Reputation: 505

MongoDB aggregation has a flexibility in the constructing of objects within pipeline. This following pipeline will help you to construct the result object you want.

However, if you are writing program, I suggest you to write a small function convert array object to an

First, to find total, I add a $group stage with _id: null to pipeline.

[
  ...your stages
  {  
    "$group": {
        "_id": null,
        "total": {
          "$sum": "$count"
        }
        "stats": {
          "$push": {
            "k": "$_id",
            "v": "$count"
          }
        },
      }
    },
  }
]

not only finding total, I also prepared an array object compatible to an operator $arrayToObject which help me make the final object.

Then the following projection make things righ.

[
  ...your stages
  {
    "$group": {
      "_id": null,
      "total": {
        "$sum": "$count"
      },
      "stats": {
        "$push": {
          "k": "$_id",
          "v": "$count"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "metric_count": {
        "$arrayToObject": {
          "$concatArrays": [
            "$stats",
            [
              {
                "k": "TOTAL",
                "v": "$total"
              }
            ]
          ]
        }
      }
    }
  }
]

As you see, I nesting pipeline operators in projection stage to contract the result object as we want. The $concatArray concat stats and total together in uniform array form then $arrayToObject convert array to final object.

I hope you will find something useful with my pipeline.

Upvotes: 1

Related Questions