如何获得每个字段(按另一个字段)MongoDB的不同字段计数?

时间:2020-09-30 16:31:51

标签: mongodb mongodb-query aggregation-framework pymongo

我有一些像这样的文件:

{ "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查询吗?谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试

  • $group按类型和项目
  • $group只需键入并计算总和
db.collection.aggregate([
  {
    $group: {
      _id: {
        type: "$type",
        item: "$item"
      }
    }
  },
  {
    $group: {
      _id: "$_id.type",
      "item-count": { $sum: 1 }
    }
  }
])

Playground