MongoDB学习笔记 - Aggregation (1)

来源:互联网 发布:淘宝运费模板删不了 编辑:程序博客网 时间:2024/06/05 03:34

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

      }
)


0 0