Get count of “loglevel” for each “name”

后端 未结 2 1230
[愿得一人]
[愿得一人] 2020-12-22 04:51

For example I have following collection:

db.names.find({})

{ \"_id\" : ObjectId(\"5768d9b4bc6f464899594570\"), \"name\"          


        
相关标签:
2条回答
  • 2020-12-22 05:12

    Remove the { "$sum": 1 } and { "$sum": 0 } expressions in your if/else conditional blocks, substitute them with the values 1 and 0 (respectively for each conditional block).

    The final pipeline should look like this, using the other $cond syntax which omits the if/else blocks:

    db.names.aggregate([
        {
            "$group": {
                "_id": "$name",
                "error": { 
                   "$sum": { 
                       "$cond": [ { "$eq": [ "$loglevel",  "ERROR" ] }, 1, 0] 
                   }
               },
               "warning":{
                   "$sum": { 
                       "$cond": [ { "$eq": [ "$loglevel", "WARNING" ] }, 1, 0 ]
                    }
               },
               "info": { 
                   "$sum": { 
                       "$cond": [ { "$eq": [ "$loglevel",  "INFO" ] }, 1, 0 ]
                   }
               }
            }
        }
    ])
    

    Or dynamically create the pipeline, given an array of possible statuses:

    var statuses = ["ERROR", "WARNING", "INFO"],
        groupOperator = { "$group": { "_id": "$name" } };
    
    statuses.forEach(function (status){ 
        groupOperator["$group"][status.toLowerCase()] = { 
           "$sum": { 
               "$cond": [ { "$eq": [ "$loglevel",  status ] }, 1, 0] 
           }
       }
    });
    
    db.names.aggregate([groupOperator]);
    

    Output

    /* 1 */
    {
        "_id" : "t1",
        "error" : 2,
        "warning" : 3,
        "info" : 1
    }
    
    /* 2 */
    {
        "_id" : "t2",
        "error" : 4,
        "warning" : 0,
        "info" : 1
    }
    
    /* 3 */
    {
        "_id" : "t3",
        "error" : 0,
        "warning" : 0,
        "info" : 1
    }
    
    0 讨论(0)
  • 2020-12-22 05:16

    If I understand correctly, you want the sum of loglevels against each name. shouldn't this help?

       db.names.aggregate([{$group:{_id:{name:"$name",loglevel:"$loglevel"},sum:{$sum:1}}}])
    
    0 讨论(0)
提交回复
热议问题