Mongodb sum the size of array fields

Include the $group operator pipeline stage after the $project step as follows:

db.profil.aggregate([
   { "$match":{ "typ": "Organisation" } },
   { "$project": {
         "fooos": { "$size": "$foos" }
   } },
   { "$group": {
       "_id": null,
       "count": {
           "$sum": "$fooos"
       }
   } }
])

This will group all the input documents from the previous $project stage and applies the accumulator expression $sum on the fooos field within the group to get the total (using your last example):

This can also be done by-passing the $project pipeline as:

db.profil.aggregate([
   { "$match": { "typ": "Organisation" } },
   { "$group": {
       "_id": null,
        "count": {
            "$sum": { "$size": "$foos" }
        }
    } }
])

Output

/* 0 */
{
    "result" : [ 
        {
            "_id" : null,
            "count" : 24
        }
    ],
    "ok" : 1
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)