1

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
}
1
  • Please provide an example of your expected output. Commented Aug 12, 2019 at 10:21

1 Answer 1

1

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
        ]
      }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.