$unwind empty array

后端 未结 2 1023
醉话见心
醉话见心 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 ] );

    0 讨论(0)
  • 2020-11-27 17:51

    With MongoDB 3.2 version and newer, the $unwind operator now has some options where in particular the preserveNullAndEmptyArrays option will solve this.

    If this option is set to true and if the path is null, missing, or an empty array, $unwind outputs the document. If false, $unwind does not output a document if the path is null, missing, or an empty array. In your case, set it to true:

    db.collection.aggregate([
        { "$unwind": {
                "path": "$solved",
                "preserveNullAndEmptyArrays": true
        } },
        { "$group": {
            "_id": "$_id",
            "login": { "$first": "$login" },
            "solved": { "$sum": "$solved.points" }
        } }
    ])
    
    0 讨论(0)
提交回复
热议问题