Mongodb sum the size of array fields

前端 未结 2 804
臣服心动
臣服心动 2020-12-14 08:31

so i have a bunch of simple documents like

{

  \"foos\": [
    ObjectId(\"5105862f2b5e30877c685c58\"),
    ObjectId(\"5105862f2b5e30877c685c57\"),
    Obje         


        
相关标签:
2条回答
  • 2020-12-14 08:41

    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
    }
    
    0 讨论(0)
  • 2020-12-14 08:55

    I know this is an old question but you can bypass project altogether if you want, so how about this?

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

    The output remains the same and it seems it's (slightly) faster.

    0 讨论(0)
提交回复
热议问题