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
You need to use aggregate update
$exists
cannot be used, hence$ifnull
usedplayground
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