How would I add a calculated field for charting

How would I add a field that rolls up IsAndroid, IsIos and IsWeb into one field and has values of ‘android’, ‘ios’, ‘web’? I have been thru the documentation regarding $cond and am having a hard time figuring this out.

This is the data

{
  "_id": "d5243083e45e47f1",
  "UserId": "1",
  "IsAndroid": true,
  "IsIos": false,
  "IsWeb": false
},
{
  "_id": "d5243083e45e47f2",
  "UserId": "2",
  "IsAndroid": false,
  "IsIos": true,
  "IsWeb": false
},
{
  "_id": "d5243083e45e47f3",
  "UserId": "3",
  "IsAndroid": false,
  "IsIos": false,
  "IsWeb": true
}

Hello @N_A_N_A20,

Welcome to The MongoDB Community Forums! :wave:

To understand your use-case better, can you please provide more details such as:

  • Exact requirements
  • Expected output document(s) with respect to the data provided.
  • What are you trying to achieve by doing this?

Regards,
Tarun

Assuming that they are mutually exclusive, you could look at:

Something like this as an aggregation:

db.getCollection('Test').aggregate([
{
    $addFields:{
        Combo:{
            $switch: {
               branches: [
                  { case: '$IsAndroid', then: 'ANDROID' },
                  { case: '$IsIos', then: 'IOS' },
                  { case: '$IsWeb', then: 'WEB' },
               ],
               default: 'Unknown'
            }
        }
    }
}
])

If you want an update then just use an update in aggregation style (i.e. surrounded with square brackets)