展开MongoDB中的多个对象数组

时间:2017-05-18 18:16:32

标签: arrays mongodb

我有3个由对象组成的数组。当我试图解开它们时,我会找回几个相同的数组。我没有收回一组干净的3个阵列作为对象。下面是我尝试解开它们之前的数组输出。有没有更好的方法来干净地解开它们?感谢。

{

  "amount_last_30_days": [
    {
      "_id": "credit card bill",
      "last_30_days": 4500.37
    }
  ],
  "amount_last_60_days": [
    {
      "_id": "credit card bill",
      "last_60_days": 1000.04
    },
    {
      "_id": "electric bill",
      "last_60_days": 7500.41
    }
  ],
  "amount_last_90_days": [
    {
      "_id": "credit card bill",
      "last_90_days": 1500.06
    },
    {
      "_id": "electric bill",
      "last_90_days": 7500.41
    }
  ],

}

最终结果:

{

 {
"_id": "credit card bill",
"last_30_days": 4500.37,
"last_60_days": 1000.04,
"last_90_days": 1500.06
},
 {
"_id": "electric bill",
"last_30_days": 0,
"last_60_days": 7500.41,
"last_90_days": 7500.41
}
}

1 个答案:

答案 0 :(得分:1)

您可以尝试$concatArrays合并所有金额。

这样的东西
db.collection.aggregate([
  {$project:{all_amounts:{$concatArrays:["$amount_last_30_days", "$amount_last_60_days", "$amount_last_90_days"]}}}
])

您可以$unwind进行进一步处理。

更新 - 将$group阶段添加到总金额。

db.collection.aggregate([
  {$project:{all_amounts:{$concatArrays:["$amount_last_30_days", "$amount_last_60_days", "$amount_last_90_days"]}}},
  {$unwind:"$all_amounts"},
  {$group:{_id:"$all_amounts._id", "last_30_days": {$sum:"$all_amounts.last_30_days"}, "last_60_days":{$sum:"$all_amounts.last_60_days"}, "last_90_days":{$sum:"$all_amounts.last_90_days"}}}
])