在mongo聚合中添加空存储桶

时间:2019-02-13 23:11:07

标签: javascript mongodb mongodb-query aggregation-framework

我有以下汇总:

const buckets = await StatisticModel.aggregate([
  {
    $bucket: {
      groupBy: '$ranking',
      boundaries: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11],
    },
  },
])

哪个返回以下对象:

[
  {
    "_id": 3,
    "count": 6
  },
  {
    "_id": 4,
    "count": 98
  },
  {
    "_id": 5,
    "count": 81
  },
  {
    "_id": 6,
    "count": 25
  },
  {
    "_id": 7,
    "count": 4
  }
]

如何添加缺少的(空)存储桶?

这是一个简单的示例,但是我有更复杂的示例,我在其中生成边界,我想将所有存储桶(不仅是填充的存储桶)返回到前端。

1 个答案:

答案 0 :(得分:0)

您可以使用以下汇总

db.collection.aggregate([
  { "$facet": {
    "data": [
      { "$bucket": {
        "groupBy": "$ranking",
        "boundaries": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
      }}
    ]
  }},
  { "$addFields": {
    "data": {
      "$map": {
        "input": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11],
        "as": "i",
        "in": {
          "_id": "$$i",
          "count": {
            "$cond": [
              { "$eq": [{ "$indexOfArray": ["$data._id", "$$i"] }, -1] },
              0,
              { "$arrayElemAt": ["$data.count", { "$indexOfArray": ["$data._id", "$$i"] }] }
            ]
          }
        }
      }
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }}
])

但是最好使用javascript

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
const array2 = [
  { "_id": 3, "count": 6 },
  { "_id": 4, "count": 98 },
  { "_id": 5, "count": 81 },
  { "_id": 6, "count": 25 },
  { "_id": 7, "count": 4 }
]

array.map((ar) => {
  const index = array2.map((e) => { return e._id }).indexOf(ar)
  if (index === -1) {
    array2.push({ _id: ar, count: 0 })
  }
})

console.log(array2)