MongoDB: count the number of items in an array

前端 未结 3 1895
执笔经年
执笔经年 2020-11-22 10:08

I have a collection where every document in the collection has an array named foo that contains a set of embedded documents. Is there currently a trivial way in

3条回答
  •  自闭症患者
    2020-11-22 10:43

    Using Projections and Groups

    db.mycollection.aggregate(
        [
            {
                $project: {
                    _id:0,
                    foo_count:{$size:"$foo"},
                }
            }, 
            {
                $group: {
                    foo_total:{$sum:"$foo_count"},
                }
            }
        ]
    )
    

    Multiple child array counts can also be calculated this way

    db.mycollection.aggregate(
        [
            {
                $project: {
                    _id:0,
                    foo1_count:{$size:"$foo1"},
                    foo2_count:{$size:"$foo2"},
                }
            }, 
            {
                $group: {
                    foo1_total:{$sum:"$foo1_count"},
                    foo2_total:{$sum:"$foo2_count"},
                }
            }
        ]
    )
    

提交回复
热议问题