如何在Mongo中合并列

问题描述 投票:1回答:1

我有这个问题,但似乎无法解决。

我的数据示例:

[
{'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,
   :
   :
   :
}
]

我想创建一个称为REST的新字段,它将是不在我输入数组([field_1, field_5])中的字段的总和。

我想要的结果是这个(对于输入[field_1, field_5]:]

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

Mongo大师请帮助!,深表感谢。谢谢!

mongodb aggregation-framework pipeline mongoose-populate
1个回答
0
投票

您可以使用$objectToArray$filter来实现:

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"
                    }
                }
            }
        }
    }
]);
© www.soinside.com 2019 - 2024. All rights reserved.