How to create a variable to avoir repeating the same condition twice?

In a $projet stage, I use a $reduce aggregation.
The same $cond aggregation is used twice.

I would like to create a variable to avoid repeating the $cond and don’t succeed to do so ?

Here is my pipeline

{
optionId: 1,
errors: {
$reduce: {
input: ‘$sizes’,
initialValue: {count:0,find:[]},
‘in’: {
count:{
$add: [’$$value.count’, {
$cond: [{
$ne: [{
$substr: [’$$this.sku’, 0, 11]
}, ‘$optionId’]
}, 1, 0]
}]
},
find:{
$concatArrays:[’$$value.find’, {
$cond: [{
$ne: [{
$substr: [’$$this.sku’, 0, 11]
}, ‘$optionId’]
}, [’$$this.sku’],[]]
}]
}
}
}
}
}

Best regards

A query is simply a JSON document.

You can use any variable you want, just like you do with any other json document. But in your case your $cond is not the same in both case. The test inside the $cond is the same but the returned values are different.

substr_var = { "$substr" : [ "$$this.sku" , 0 , 11 ] }
test_var = { "$ne" : [  substr_var , "$optionId" ] }
count = { "$add" : [
  "$$value.count" ,
  { "$cond" : [ test_var , 1 , 0 ] }
] }
find : { "$concatArrays" : [
  "$$value.find" ,
  { "$cond" : [ test_var , ["$$this.sku"] , [] ] }
} ]

// here is my pipeline
{
  "optionId" : 1,
  "errors" : {
    "$reduce" : {
      "input" : "$sizes" ,
      "initialValue" : { "count" : 0 , "find": [] } ,
      "in": { count , find }
    }
  }
}

Hi,

Thank for your answer.
My query is running !

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.