$ group与嵌套数组元素

时间:2018-07-12 02:25:47

标签: javascript mongodb aggregation-framework

想知道如何使用MongoDB的聚合来汇总每个reason_id的计数:

我想知道“ reason_id = KW7Kcsv7835YZeE3n”有2个计数,而“ reason_id = KNcKQCjhFzha3oLfE”有1个计数。

这是我的数据:

[
  {
    "_id": "2DLQFJLbZScBXpSam",
    "toilet_id": "bJsyfh3TCvpTzE2mJ",
    "reason_ids": [
      "KNcKQCjhFzha3oLfE",
      "KW7Kcsv7835YZeE3n"
    ],
    "score_id": null,
    "toilet": {
      "_id": "bJsyfh3TCvpTzE2mJ",
      "name": "Toilet_M_1",
      "gender": "m",
      "mac_address": "11:11:11:11:11:11"
    }
  },

  {
    "_id": "akjsbcjascklsacas",
    "toilet_id": "bJsyfh3TCvpTzE2mJ",
    "reason_ids": [
      "KW7Kcsv7835YZeE3n"
    ],
    "score_id": null,
    "toilet": {
      "_id": "fsgndgklndsdsdsd",
      "name": "Toilet_F_1",
      "gender": "f",
      "mac_address": "11:11:11:11:11:11"
    }
  },
]

1 个答案:

答案 0 :(得分:1)

您可以尝试

db.collection.aggregate([
  {
    "$unwind": "$reason_ids"
  },
  {
    "$group": {
      "_id": "$reason_ids",
      "count": {
        "$sum": 1
      }
    }
  }
])

输出

[
  {
    "_id": "KW7Kcsv7835YZeE3n",
    "count": 2
  },
  {
    "_id": "KNcKQCjhFzha3oLfE",
    "count": 1
  }
]

尝试here