Help with Charts

Hello! I have the following example document:

{
    is_type_a: false,
    is_type_b: false,
    is_type_c: true,
    points: 20
}

I want to create a Text > Number Chart that will display a new calculatedField Totals following this rule:

  • For each document that is_type_a == true and is_type_b == True, add 180 to the new calculatedField Totals

  • For each document that is_type_a == false or is_type_b == false and is_type_c == true, add the field points to the new calculatedField Totals

I am new to the aggregation pipeline and charts, so I am a bit confused on how to achive this. I only know how to create simple calculatedFields and display them.
Any thoughts ?

Hi @Thiago_Benine and welcome in the MongoDB Community :muscle: !

I’m not sure I completely understood the maths you are trying to do but at least this should put you on the right track hopefully.

[
  {
    '$addFields': {
      'totals': {
        '$switch': {
          'branches': [
            {
              'case': {
                '$and': [
                  {
                    '$eq': [
                      '$a', true
                    ]
                  }, {
                    '$eq': [
                      '$b', true
                    ]
                  }
                ]
              }, 
              'then': 180
            }, {
              'case': {
                '$and': [
                  {
                    '$eq': [
                      '$a', false
                    ]
                  }, {
                    '$eq': [
                      '$b', false
                    ]
                  }, {
                    '$eq': [
                      '$c', true
                    ]
                  }
                ]
              }, 
              'then': '$points'
            }
          ], 
          'default': 0
        }
      }
    }
  }
]

Here it is in action in MongoDB Compass:

Cheers,
Maxime.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.