如何通过另一个字段MongoDB(分组)获得一个字段的distinct计数?

如何通过另一个字段MongoDB(分组)获得一个字段的distinct计数?,mongodb,mongodb-query,aggregation-framework,pymongo,Mongodb,Mongodb Query,Aggregation Framework,Pymongo,我有以下文件: { "type" : "A", "item" : "I1"} { "type" : "A", "item" : "I2"} { "type" : "A", "item" : "I2"} { "type" : "A&

我有以下文件:

{ "type" : "A", "item" : "I1"}
{ "type" : "A", "item" : "I2"}
{ "type" : "A", "item" : "I2"}
{ "type" : "A", "item" : "I2"}
{ "type" : "A", "item" : "I3"}
{ "type" : "B", "item" : "I4"}
{ "type" : "B", "item" : "I4"}
{ "type" : "B", "item" : "I5"}

我想找到每个“类型”的不同“项”的计数,如下所示:

{ "type" : "A", "item-count" : 3}
{ "type" : "B", "item-count" : 2}
你知道如何编写MongoDB查询吗?谢谢

你可以试试

  • $group
    按类型和项目
  • $group
    仅按类型和计数总和

db.collection.aggregate([
  {
    $group: {
      _id: {
        type: "$type",
        item: "$item"
      }
    }
  },
  {
    $group: {
      _id: "$_id.type",
      "item-count": { $sum: 1 }
    }
  }
])