$unwind empty array

后端 未结 2 1044
醉话见心
醉话见心 2020-11-27 17:08

I have a collection of users where each document has following structure:

{
  \"_id\": \"\",
  \"login\": \"xxx\",
  \"solved\": [
    {
      \"pr         


        
2条回答
  •  抹茶落季
    2020-11-27 17:38

    Here is the solution - it assumes that the field "solved" is either absent, is equal to null or has an array of problems and scores solved. The case it does not handle is "solved" being an empty array - although that would be a simple additional adjustment you could add.

    project = {$project : {
            "s" : {
                "$ifNull" : [
                    "$solved",
                    [
                        {
                            "points" : 0
                        }
                    ]
                ]
            },
            "login" : 1
        }
    };
    unwind={$unwind:"$s"};
    group= { "$group" : {
            "_id" : "$_id",
            "login" : {
                "$first" : "$login"
            },
            "score" : {
                "$sum" : "$s.points"
            }
        }
    }
    

    db.students.aggregate( [ project, unwind, group ] );

提交回复
热议问题