mongodb- 汇总以获得计数。

mongodb- aggregate to get counts.

我一直在学习 mongodb,但在编写查询时有点卡住了。

我有以下合集:

{
    _id : 1,
    House: A,
    inventory: [
        {
            place: Kitchen,
            item: fridge
        },
        {
            place: Kitchen,
            item: stove
        },
        {
            place: Kitchen,
            item: TV
        },
        {
            place: Bedroom,
            item: bed
        },
        {
            place: Bedroom,
            item: TV
        }
    ]
},
{
    _id : 2,
    House: B,
    inventory: [
        {
        ....
        }
    ]
},

我如何编写查询 return "places" 和 "items" 的计数?所以输出应该是这样的:
{id: Kitchen, PlaceCount: 3, itemCount: 3} - 3 个厨房,3 个物品(冰箱,炉灶,电视)
{id: Bedroom, PlaceCount: 2, itemCount: 2} - 2 间卧室,2 件物品(床,电视)

我需要在每个地方计算电视数量。

您应该使用 Aggregation Pipeline,它允许您在传递数组的多个步骤中聚合数据。

您的聚合应该是:

db.your_collection.aggregate([
  {$unwind: "$inventory" },
  {$group: { _id: "$inventory.place", placeCount:{$sum : 1}, items : {$push: "$inventory.item"}}},
  {$project: { placeCount: 1, itemsCount : {$size: "$items"}}}
])

解释:

  1. $unwind 为您的每个库存元素生成一个结果
  2. $group the unwinded inventory elements by place, requiring a count (using $sum) and an array of items (still by place, using $push)
  3. $project the following data of your grouped results from previous step: the placeCount and the size (using $size) 的项目数组,即 itemsCount