Can the MongoDB aggregation framework $group return an array of values?

前端 未结 3 1992
别跟我提以往
别跟我提以往 2020-12-13 11:14

How flexible is the aggregate function for output formatting in MongoDB?

Data format:

{
        \"_id\" : ObjectId(\"506ffffd1900a47d802702a904\"),
            


        
3条回答
  •  不思量自难忘°
    2020-12-13 11:50

    MongoDB 2.6 made this a lot easier by introducing $map, which allows a simplier form of array transposition:

    db.metrics.aggregate([
       { "$match": {
           "array_serial": array, 
           "port_name": { "$in": ports},
           "datetime": { "$gte": from, "$lte": to }
        }},
        { "$group": {
            "_id": "$port_name",
            "data": {
                "$push": {
                    "$map": {
                        "input": [0,1],
                        "as": "index",
                        "in": {
                            "$cond": [
                                { "$eq": [ "$$index", 0 ] },
                                "$datetime",
                                "$metric"
                            ]
                        }
                    }
                }
            },
            "count": { "$sum": 1 }
        }}
    ])
    

    Where much like the approach with $unwind, you supply an array as "input" to the map operation consisting of two values and then essentially replace those values with the field values you want via the $cond operation.

    This actually removes all the pipeline juggling required to transform the document as was required in previous releases and just leaves the actual aggregation to the job at hand, which is basically accumulating per "port_name" value, and the transformation to array is no longer a problem area.

提交回复
热议问题