MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Kann das MongoDB-Aggregationsframework $group ein Array von Werten zurückgeben?

Das Kombinieren von zwei Feldern zu einem Array von Werten mit dem Aggregation Framework ist möglich, aber definitiv nicht so einfach, wie es sein könnte (zumindest bei MongoDB 2.2.0).

Hier ist ein Beispiel:

db.metrics.aggregate(

    // Find matching documents first (can take advantage of index)
    { $match : {
        'array_serial' : array, 
        'port_name' : { $in : ports},
        'datetime' : { $gte : from, $lte : to}
    }},

    // Project desired fields and add an extra $index for # of array elements
    { $project: {
        port_name: 1,
        datetime: 1,
        metric: 1,
        index: { $const:[0,1] }
    }},

    // Split into document stream based on $index
    { $unwind: '$index' },

    // Re-group data using conditional to create array [$datetime, $metric]
    { $group: {
        _id: { id: '$_id', port_name: '$port_name' },
        data: {
            $push: { $cond:[ {$eq:['$index', 0]}, '$datetime', '$metric'] }
        },
    }},

    // Sort results
    { $sort: { _id:1 } },

    // Final group by port_name with data array and count
    { $group: {
        _id: '$_id.port_name',
        data: { $push: '$data' },
        count: { $sum: 1 }
    }}
)