How to merge columns in Mongo

Viewed 30

I've got this problem and I can't seem to solve it.

A sample of my data:

[
{'item': 'U',
'field_1': 3,
'field_2': 1,
'field_3': 1,
'field_4': 2,
'field_5': 5,
   :
   :
   :
},
{'item': 'Y',
'field_1': 9,
'field_2': 2,
'field_3': 3,
'field_4': 5,
'field_5': 1,
   :
   :
   :
}
]

I would like to create a new field called REST, which will be the sum of fields not in my input array ([field_1, field_5]).

My desired result is this (for input [field_1, field_5]):

[
{'item': 'U',
'REST': 13,
},
{'item': 'Y',
'REST': 20
}
]

Mongo gurus please help!, Deeply appreciate it. Thanks!

1 Answers

You can use $objectToArray and $filter to achieve this:

db.collection.aggregate([
    {
        $addFields: {
            rootAsArray: {
                $filter: {
                    input: {$objectToArray: "$$ROOT"},
                    as: "field",
                    cond: {
                        $and: [
                            {$ne: ["$$field.k", "_id"]},
                            {$ne: ["$$field.k", "item"]},
                            ...any other field that's not relevant, you can also just add these to input arr ...

                            {$not: {$setIsSubset: [["$$field.k"], ["field_1", "field_5"]]}}
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            item: "$item",
            OTHER: {
                $sum: {
                    $map: {
                        input: "$rootAsArray",
                        as: "value",
                        in: "$$value.v"
                    }
                }
            }
        }
    }
]);
Related