MongoDB 聚合 $lookup 不适用于 $group

MongoDB aggregate $lookup not working with $group

我的数据库中有两个集合:类别和产品,我想列出所有类别和它们拥有的产品数量。在产品架构中,我有 'foreign key' 指向类别集合中的 _id 列,所以我形成了这样的查询:

db.categories.aggregate(
  {
    $lookup:{
        from:"products",
        localField:"_id",
        foreignField:"product_category",
        as:"category_products"
     }
   }
)

结果我收到了这个:

{ _id: ObjectId("613cde06e806c050fcf073eb"),
  name: 'Drinks',
  category_products: 
   [{ _id: ObjectId("61476348e4dfdb0d54d38a29"),
       product_name: 'Alpro Almond Miln',
       product_price: 1.99,
       product_category: ObjectId("613cde06e806c050fcf073eb"),
       createdAt: 2021-09-19T16:20:24.269Z,
       updatedAt: 2021-09-19T16:20:24.269Z,
       __v: 0 },
     { _id: ObjectId("6147a974e4dfdb0d54d38aee"),
       product_name: 'Coca Cola 2l',
       product_price: 1.99,
       product_category: ObjectId("613cde06e806c050fcf073eb"),
       createdAt: 2021-09-19T21:19:48.105Z,
       updatedAt: 2021-09-19T21:19:48.105Z,
       __v: 0 }]}

现在我想计算这个名为 'Drinks' 的类别的产品数量。我形成了这样的查询:

  db.categories.aggregate(
  {
    $lookup:{
        from:"products",
        localField:"_id",
        foreignField:"product_category",
        as:"category_products"
     }
   },   
    {
     $group : {
         _id : '$name',
         num_of_products : {
          $sum : "$category_products._id" 
        } 
      }
    }
)

结果我得到:

{ _id: 'Drinks', num_of_products: 0 }

所以我的问题是如何正确计算集合中每个类别的产品数量。我希望得到这样的结果:

{ _id: 'Sweets', num_of_products: 2 }
{ _id: 'Snacks', num_of_products: 5 }
{ _id: 'Drinks', num_of_products: 1 }
{ _id: 'Coffee', num_of_products: 6 }

看起来您不需要 $group,您在数组中有类别产品,因此使用它的 $size 看起来就足够了。

尝试将此添加 $project 作为下一阶段。

*我不确定你是否想要这个,因为在你的示例数据中没有糖果、零食、只有咖啡的饮料,而你有 2 杯饮料,并且表明你只期望 1 杯饮料

 {
  "$project" : {
    "_id" : 0,
    "name" : "$name",
    "num_of_products" : {
      "$size" : "$category_products"
    }
  }
}