cursor = db.flow.aggregate([
    {
        $match : {
            dir       : "A",
            l4Proto   : 17,
            timeFirst : { $gte : time_from },
            timeLast  : { $lte : time_to },
        }
    },
    {
        $project : {
            port : {
                $cond : {
                    if : {
                        $eq : [
                            { $mod : [ "$flowStat", 2 ] },
                            0
                        ]
                    },
                    then : "$srcPort",
                    else : "$dstPort"
                }
            },
            pkts : {
                $cond : {
                    if : {
                        $eq : [
                            { $mod : [ "$flowStat", 2 ] },
                            0
                        ]
                    },
                    then : "$pktsSnt",
                    else : "$pktsRcvd"
                }
            }
        }
    },
    {
        $group : {
            _id : "$port",
            count : { $sum : "$pkts" }
        }
    },
    {
        $addFields : {
            sort_id: {
                $multiply : [
                    sort_order,
                    "$count"
                ]
            },
        }
    },
    {
        $sort : { sort_id : -1 }
    },
    {
        $limit : n
    }
])

cursor.forEach(
    function(e) {
        print(
              e._id + "\t"
            + e.count
        )
    }
)
