假设我们有A, B, C ,D and E
我需要的变量来匹配遵守以下规则的文档:
!A AND [B OR (if C then if C && D then check if field1 matches 'abc' AND field2 matches 'def' else check if field1 matches 'abc') OR (if D then if D && E then check if field2 matches 'def' AND field3 matches 'ghi' else check if field2 matches 'def' else if E check if field3 matches 'ghi')]
我的文档如下所示:
{
_id: ObjectId('123123123123123123123123'),
field1: 'abc',
field2: 'asd',
field3: 'qwe',
checker:{
A: false,
B: false,
C: true,
D: true,
E: false
}
}
请记住:当A为真时休息为假,B为真休息为假,C为真D仅可能为真休息为假,E为真D仅可能为真休息为假,当D为真时仅C或 E 可能为真,其余为假。
我在舞台上的 mongo 上试过这个,$match但似乎我做得不对
{
$and:[
{ A: false },
{
$or:[
{ B: true },
{
$cond: {
if: { C: true },
then: {
$cond: {
if: {
$and: [{ C: true },{D: true}]
},
then:{
field1: 'abc',
field2: 'def'
},
else:{
field1: 'abc'
}
}
}
}
},
{
$cond: {
if: { D: true },
then: {
$cond: {
if: {
$and: [{ D: true },{E: true}]
},
then:{
field2: 'def',
field3: 'ghi'
},
else:{
field2: 'def'
}
}
},
else{
field3: 'ghi'
}
}
}
]
}
]
}
他们说这格式不正确,即使我觉得没问题。问题是$cond运营商。如果我删除它们,它会起作用,但它只检查 2 个变量,我需要完成每个案例。
从第一个表达式可以看出,它看起来像这样:
if(C){
if(C && D){
match({field1: 'abc', field2: 'def'})
}else{
match({field1: 'abc'})
}
}
另一个 $cond 与上面的类似。
更新
不需要使用 $cond 运算符(在我的示例中未正确使用)
通过不同的方式解决了这个问题:
$and :[
{ A: false },
{
$or:[
{ B: true },
{ $or: [ {C: false}, { field1: 'abc'} ] }
{ $or: [ {D: false}, { field2: 'def'} ] }
{ $or: [ {E: false}, { field1: 'ghi'} ] }
]
}
]