Mongodb Aggregation Framework | Group over multiple values?

前端 未结 1 1698
故里飘歌
故里飘歌 2020-12-01 10:34

I would like to use mongoDB\'s Aggregation Framework to run what in SQL would look a bit like:

SELECT SUM(A), B, C from myTable GROUP BY B, C;
相关标签:
1条回答
  • 2020-12-01 11:28

    OK, so the solution is to specify an aggregate key for the _id value. This is documented here as:

    You can specify a single field from the documents in the pipeline, a previously computed value, or an aggregate key made up from several incoming fields.

    But it doesn't actually define the format for an aggregate key. Reading the earlier documentation here I saw that the previous collection.group method could take multiple fields and that the same structure is used in the new framework.

    So, to group over multiple fields you could use _id : { success:'$success', responseCode:'$responseCode', label:'$label'}

    As in:

    resultsCollection.aggregate(
    { $match : { testid : testid} },
    { $skip : alreadyRead },
    { $project : {
            timeStamp : 1 ,
            label : 1,
            responseCode : 1 ,
            value : 1,
            success : 1
        }},
    { $group : {
            _id :  { success:'$success', responseCode:'$responseCode', label:'$label'},
            max_timeStamp : { $timeStamp : 1 },
            count_responseCode : { $sum : 1 },
            avg_value : { $sum : "$value" },
            count_success : { $sum : 1 }
        }}
    );
    
    0 讨论(0)
提交回复
热议问题