Line chart from date picker

This aggregation creates a line chart from the date picker in a data collection.

Result:


Code

Group #1

{ "_id": { "month": { "$month": "$answers.date" }, "year": { "$year": "$answers.date" } }, "count": { "$sum": "$answers.totalnumberofParticipants" } }

Sort

{ "_id.year": 1, "_id.month": 1 }

Group #2

{ "_id": "$result", "events": { "$push": { "x": { "$concat": [ { "$toString": "$_id.month" }, "-", { "$toString": "$_id.year" } ] }, "y": "$count" } } }

Project

Unwind

ReplaceRoot

Explanation

  1. Grouping by Month and Year:

    • The data is grouped based on the month and year of the "answers.date" field.

    • The "$group" stage groups the data using the "$month" and "$year" operators.

    • The grouped data will have an "_id" field containing the month and year information, and a "count" field representing the sum of "answers.totalnumberofParticipants" within each group.

  2. Sorting by Year and Month:

    • The "$sort" stage sorts the grouped data based on the "_id.year" field in ascending order, followed by the "_id.month" field in ascending order.

  3. Grouping by Result and Creating Events:

    • The data is grouped again, this time using the "result" field.

    • The "$push" operator creates an array of "events" containing the "x" and "y" values.

    • The "x" value is a concatenation of the "_id.month" and "_id.year" fields, converted to strings.

    • The "y" value is the "count" field from the previous grouping.

  4. Projecting the Result:

    • The "$project" stage specifies which fields to include in the output.

    • The "_id" field is excluded.

    • The "result" field is created as an array containing an object with "id" and "data" fields.

    • The "id" field is set to "Participants".

    • The "data" field is set to the "events" array created in the previous stage.

  5. Unwinding the Result:

    • The "$unwind" stage flattens the "result" array, creating separate documents for each element.

  6. Replacing the Root:

    • The "$replaceRoot" stage promotes the "result" field to become the new root of the document.