如何在MongoDB中有条件地添加新字段?



我有一个aggregation pipeline,我想在其中添加基于某些条件的新字段。我的管道是这样的

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

现在我想添加一个新的字段record_type基于条件,如果contract_proposal_metadata存在,那么记录类型将是'renew ',如果risk_info_request_metadata存在,那么record_type将是request

我怎样才能做到这一点?

您不是有条件地添加新字段。您总是在添加字段,只是使用不同的值。

$cond操作符根据第一个参数的条件返回2个值中的1个。

对于$match阶段,您已经知道$exist,在聚合表达式中使用的等效操作符是$type

[
{ // match stage
.....
},
{  // adding the field
$addFields: {
record_type: { $cond: { 
if: { $eq: [ { $type: "$contract_proposal_metadata" }, "missing" ] }, 
then: "request", 
else: "renewal" 
} }
}
}
]

您需要使用聚合更新

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. 从mongo 4.2+
  2. $exists不能使用,因此$ifnull使用
  3. 游乐场

最新更新