Mongodb sum the size of array fields

前端 未结 2 813
臣服心动
臣服心动 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: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.

提交回复
热议问题