我有一些像这样的文件:
{ "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查询吗?谢谢
答案 0 :(得分:1)
您可以尝试
$group
按类型和项目$group
只需键入并计算总和db.collection.aggregate([
{
$group: {
_id: {
type: "$type",
item: "$item"
}
}
},
{
$group: {
_id: "$_id.type",
"item-count": { $sum: 1 }
}
}
])