根据ids统计mongo聚合中有多少用户

Based on ids, count how many user in mongo aggregation

所以我有一个 collection 这样的:

    {
     'region': '111',
     'fruit': 'apple'
    }
    {
     'region': '111',
     'fruit': 'apple'
    }
    {
     'region': '222',
     'fruit': 'orange'
    }
    {
     'region': '222',
     'fruit': 'apple'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
{
     'region': '333',
     'fruit': 'orange'
    }

我需要这样

{'111': 1, '222': 2, '333': 2} 哪个键是宗教,值应该是该宗教的不同水果的数量。 333 有 3 个葡萄和 1 个橙子,但它应该作为 2 个,因为它有 2 个不同的水果。 谁能帮帮我...

获取您请求的输出似乎过于复杂,尤其是希望区域值成为键。聚合管道已经提供了一种获取分组总数的方法,这将提供 document-per-region 每个区域的总数。您可以使用两个小组赛阶段来获得您要查找的总数,如下所示:

[
  {
    $group: 
    {
      _id: { region: "$region", fruit: "$fruit" },
      count: { $sum: 1 }
    }
  },
  {
    $group:
    {
      _id: "$_id.region",
      count: { $sum: 1 }
    }
  }
]

此聚合的输出如下所示:

{ _id: '111', count: 1 },
{ _id: '222', count: 2 },
{ _id: '333', count: 2 }

我怀疑这会更容易使用输出,因为返回的文档数是区域的数量(而不是必须计算您在问题中要求返回的单个文档中的键数).