在Aggregate开关的情况下,如何在Mongodb中使用match as with Regular Expressi



这是我所做的。

内部$AddFields

{
ClientStatus:{
$switch: {
branches: [
{ case: {
$eq:
[
"$CaseClientStatus",
/In Progress/i              
]},
then:'In Progress'
},
{ case: {
$eq:
[
"$CaseClientStatus",
{regex:/Cancelled/i}
],
},then:'Cancelled'},
{ case: {$eq:['$CaseClientStatus','Complete - All Results Clear']}, then:'Complete'},
{ case: {$eq:['$CaseClientStatus','Case on Hold']}, then:'Case on Hold'}
],
default: 'Other'
}}
}

但我的ClientStatus只显示Complete、Other、Case On Hold,而不是用regex指定的。alhough字段包含这些单词。

这是单据

{
"CandidateName": "Bruce  Consumer",  
"_id": "61b30daeaa237672bb7a17cc",
"CaseClientStatus": "Background Check Case In Progress",
"TAT": "N/A",
"CaseCloseDate": null,
"FormationAutomationStatus": "Automated",
"MethodOfDataSupply": "Automated",
"Status": "Background Case In Progress",
"CreatedDate": "2021-12-10T08:19:58.389Z",  
"OrderId": "Ord3954",
"PONumber": "",
"Position": "",
"FacilityCode": "",
"IsCaseClose": false,
"Requester": "Shah Shah",
"ReportErrorList": 0
}

假设您使用的是4.2或更高版本(因为4.2大约在2年前就发布了,所以应该使用(,那么$regexFind函数就可以满足您的需求。在4.2之前,regex仅在$match运算符中可用,在复杂的agg表达式中不可用。您上面的尝试是令人钦佩的,但//regex语法是而不是做您认为应该做的事情。值得注意的是,{regex:/Cancelled/i}只是创建一个具有关键字regex和字符串值/Cancelled/i(包括斜线(的新对象,这显然不等于$CaseClientStatus中的任何值。这里有一个解决方案:

ClientStatus:{
$switch: {
branches: [
{ case: {
$ne: [null, {$regexFind: {input: "$CaseClientStatus", regex: /In Progress/i}}]
}, then:'In Progress'},
{ case: {
$ne: [null, {$regexFind: {input: "$CaseClientStatus", regex: /Cancelled/i}}]
},then:'Cancelled'},
{ case: {$eq:['$CaseClientStatus','Complete - All Results Clear']}, then:'Complete'},
{ case: {$eq:['$CaseClientStatus','Case on Hold']}, then:'Case on Hold'}
],
default: 'Other'
}}

看起来你正试图采取一种有点自由的状态";描述";字段,并从中创建一个强枚举状态。我建议您的$ClientStatus输出更像代码,例如IN_PROGRESS, COMPLETE, CXL等。消除大小写,当然还有空格。

最新更新