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" }
}
}
)