MongoDB里面经常需要做一些统计任务,这里使用Aggregate 内嵌文档的例子,例如下面的文档,我们希望找到type 1的colors 的数量总和
inventory collection 如下:
{"_id" : 1, "item" : "ABC1","type",1, "description" : "product 1", colors: [ "blue","black", "red" ] }
{ "_id" : 2, "item" : "ABC2","type",1, "description": "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1","type",1, "description" : "product 3", colors: [ ] }
db.inventory.aggregate (
{
$match: {
"type": 1
},
{
$project: {
type: 1,
numberOfColors: { $size:"$colors" }
},
{
$group: {
_id: "$type",
totalCount: { $sum:"$numberOfColors" }
}
}
)
本文介绍如何使用MongoDB的聚合框架来统计特定类型文档中颜色属性的数量总和。通过$match, $project和$group阶段实现对inventory集合内type1项的颜色数量进行计算。
3万+

被折叠的 条评论
为什么被折叠?



