skip to Main Content

I have an aggregation pipeline in which i want to add new field based on certain condition. My pipeline is like this

[
  { // match stage

    $or:[
     { 
       $and: [
         {placement: {'$nin': [-1,-2]}},
         {contract_proposal_metadata : {$exists: true}}
       ]
     },
     { 
       risk_info_request_metadata: {$exists: true}
     }
   ]

  } 
]

Now i want to add a new field record_type based on the condition that if contract_proposal_metadata exists so record type will be ‘renewal’ and if risk_info_request_metadata is exists then record_type will be request.

How can i achieve this?

2

Answers


  1. You need to use aggregate update

    db.collection.update({
          placement: { //Your match goes here
            "$nin": [
              -1,
              -2
            ]
          },
          
        },
        [
          {
            $set: {
              status: {
                $switch: {
                  branches: [
                    { //update condition goes here
                      case: {
                        $ifNull: [
                          "$contract_proposal_metadata",
                          false
                        ]
                      },
                      then: "renewal"
                    },
                    {
                      case: {
                        $ifNull: [
                          "$risk_info_request_metadata",
                          false
                        ]
                      },
                      then: "request"
                    },
                    
                  ],
                  default: ""
                }
              }
            }
          }
        ],
        {
          multi: true
        })
    
    1. It supported from mongo 4.2+
    2. $exists cannot be used, hence $ifnull used

    playground

    Login or Signup to reply.
  2. You are not adding new field conditionally. You are always adding the field, just with different values.

    There is $cond operator which returns 1 of 2 values depending on condition in the first argument.

    You already know $exist for the $match stage, and the equivalent operator to use in aggregation expression is $type

    [
       { // match stage
           .....
       },
       {  // adding the field
          $addFields: {
              record_type: { $cond: { 
                  if: { $eq: [ { $type: "$contract_proposal_metadata" }, "missing" ] }, 
                  then: "request", 
                  else: "renewal" 
              } }
          }
       }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search