I am facing a challenge with my array of objects named "extra" that have different properties: some objects include the property "plus" while others do not. I am attempting to split this "extra" array into two separate arrays - one called "cheap" containing objects without the "plus" property, and another named "exp" which includes only objects with the "plus" property. I believe I can achieve this using the $reduce method in MongoDB aggregate along with $concatArrays by using $cond to check for the existence of the "plus" property. Here is an example of what I have tried:
Example data:
{
extra: [
{
description: "laces",
type: "exterior",
plus: '200'
},
{
description: "sole",
type: "interior"
},
{
description: "logo",
type: "exterior"
},
{
description: "stud",
type: "exterior",
plus: '450'
}
],
}
{
$project: {
extra: {
$reduce: {
input: ['$extra'],
initialValue: {cheap: [], exp: []},
$cond: {
if: {$eq: ['$$this.plus', null]},
then: {
in: {
cheap: {
$concatArrays: ['$$value.cheap', '$$this'],
},
},
},
else: {
in: {
exp: {
$concatArrays: ['$$value.exp', '$$this'],
},
},
},
},
},
},
},
}
Despite trying several variations of the $cond section, I have been unsuccessful in getting it to work. Any assistance would be greatly appreciated. Thank you, K.