Sydney
Sydney

Reputation: 12212

Mongo aggregation: add conditional fields

I have an aggregtion pipeline with several stages. After those stages, the simplified result is like that:

{
    feature1: [{random: 125}],
    feature2: [{a:"fsfs", val: [125]}]
}

I want to add a new field type which is set based on these conditions:

The content of feature1 and feature2 arrays is not significant, the type is based on either the arrays are populated or not.

My idea is to use a $addFields stage with a $cond operator but I can't figure out the syntax.

Upvotes: 3

Views: 1937

Answers (1)

s7vr
s7vr

Reputation: 75934

Use $switch.

Something like

{
  "$addFields":{
    "type":{
      "$switch":{
        "branches":[
          {
            "case":{
              "$and":[
                {"$gt":[{"$size":"$feature1"},0]},
                {"$gt":[{"$size":"$feature2"},0]}
              ]
            },
            "then":"back"
          },
          {
            "case":{
             "$gt":[{"$size":"$feature1"},0]
            },
            "then":"front"
          }
        ],
        "default":"none"
      }
    }
  }
}

Upvotes: 3

Related Questions