分组并保留原始字段

时间:2020-09-18 14:42:18

标签: mongodb aggregation-framework

我在mongodb聚合中看到了,特别是在y中,我们可以使用累加器来创建新字段。但是我想要旧钥匙

假设我有此数据

$group

然后聚合应该像

[
   { name: "My Plan 101", billingCycle: 'day', amount: 1, credits: 100, price: 7 },
   { name: "My Plan 102", billingCycle: 'day', amount: 1, credits: 150, price: 10 },
   { name: "My Plan 103", billingCycle: 'day', amount: 2, credits: 150, price: 15 },
   { name: "My Plan 104", billingCycle: 'month', amount: 3, credits: 150, price: 15 },
   { name: "My Plan 105", billingCycle: 'month', amount: 3, credits: 200, price: 20 },
]

1 个答案:

答案 0 :(得分:0)

我在mongodb聚合上做了很多尝试,但是无法解决,所以我为此使用了lodash。

let plans = await Plan.find()
plans = _.groupBy(plans, 'billingCycle');

for (const billingCyle in plans) {
  let $plans = plans[billingCyle];
  plans[billingCyle] = _.groupBy($plans, "amount")
}
console.log(plans)

上面的片段解决了我的问题