Alka
Alka

Reputation: 267

How to divide the elements inside array using mongodb aggregation

I have used aggregation to find below output.
Next step is to divide the values of elements present in each array.

{
    "_id" : {
        “type”:”xxx”,
        "year" : 2019
    },
    "allvalues" : [
        {
            "label" : “used”,
            "value" : 50
        },
        {
            "label" : “total”,
            "value" : 58
        }
    ]
}
{
    "_id" : {
        “type”:”yyy”,
        "year" : 2019
    },
    "allvalues" : [
        {
            "label" : “used”,
            "value" : 63.214285714285715
        },
        {
            "label" : “total”,
            "value" : 59.535714285714285
        }
    ]
}

How to write the query to divide used/total in each doc.
For first doc it is 50/58 and second doc it is 63.21/59.53.
The structure of json remains constant.
Output should look like below:

{
    “type”:”xxx”,
    "year" : 2019,
    “result” : 0.8
}
{
    “type”:”yyy”,
    "year" : 2019,
    “result” : 1.06
}

Upvotes: 1

Views: 1098

Answers (1)

sushant mehta
sushant mehta

Reputation: 1274

Add this in the aggregate pipeline after you get above input first you need to use $filter and $arrayElemAt to get used and total's value after that as divide doesn't give fixed decimal place, I've used $trunc to make value to 2 decimal fixed place

  {
    $project: {
      _id: 1,
      used: {
        $arrayElemAt: [
          {
            $filter: {
              input: "$allvalues",
              as: "item",
              cond: {
                $eq: [
                  "$$item.label",
                  "used"
                ]
              }
            }
          },
          0
        ]
      },
      total: {
        $arrayElemAt: [
          {
            $filter: {
              input: "$allvalues",
              as: "item",
              cond: {
                $eq: [
                  "$$item.label",
                  "total"
                ]
              }
            }
          },
          0
        ]
      },

    }
  },
  {
    $project: {
      _id: 1,
      result: {
        $divide: [
          {
            $trunc: {
              $multiply: [
                {
                  $divide: [
                    "$used.value",
                    "$total.value"
                  ]
                },
                100
              ]
            }
          },
          100
        ]
      }
    }
  }

Upvotes: 1

Related Questions