如何按两个不同的字段进行分组

时间:2018-01-28 12:37:06

标签: mongodb mongodb-query aggregation-framework

我的收藏中的文件结构如下:

    [

    {
    sender: 'A', recipient: 'B', date: New MongoDate(1), contents: 'Blablabla1'
    },

    {
    sender: 'B', recipient: 'A', date: New MongoDate(2), contents: 'Blablabla2'
    },

    {
    sender: 'A', recipient: 'C', date: New MongoDate(4), contents: 'Blablabla1'
    },

    {
    sender: 'C', recipient: 'A', date: New MongoDate(3), contents: 'Blablabla2' 
    }

    {
    sender: 'C', recipient: 'D', date: New MongoDate(3), contents: 'Blablabla2'
    }


    ]

我想按收件人或发件人进行分组,并从每个组中只选择一个日期最长的文档

例如,我想获得这样的结果:

[

{
_id: 'AB', sender: 'B', recipient: 'A', date: 2, contents: 'Blablabla2', count: 2
},

{
_id: 'AC', sender: 'A', recipient: 'C',  date: 4, contents: 'Blablabla1', count: 2
}

{
_id: 'CD', sender: 'C', recipient: 'D',  date: 3, contents: 'Blablabla2', count: 1
}

]

怎么做?我不知道如何分组两个不同的领域..

1 个答案:

答案 0 :(得分:1)

你可以尝试这种聚合

  1. $sort - 按日期排序以获取$last
  2. 中的$group元素
  3. $group - 按字母顺序按$cond _id和$concat进行分组
  4. $sort - 按_id升序排序结果
  5. 管道

    db.col.aggregate(
        [
            {$sort : { date : 1}},
            {$group : {
                _id : { $cond : [ {$gt : ["$sender", "$recipient"]}, {$concat : ["$recipient", "$sender"]}, {$concat : ["$sender", "$recipient"]}]},
                sender : {$last : "$sender"},
                recipient : {$last : "$recipient"},
                date : {$last : "$date"},
                contents : {$last : "$contents"},
                count : {$sum : 1}
             }
            },
            {$sort : { _id : 1}},
        ]
    )
    

    结果

    { "_id" : "AB", "sender" : "B", "recipient" : "A", "date" : 2, "contents" : "Blablabla2", "count" : 2 }
    { "_id" : "AC", "sender" : "A", "recipient" : "C", "date" : 4, "contents" : "Blablabla1", "count" : 2 }
    { "_id" : "CD", "sender" : "C", "recipient" : "D", "date" : 3, "contents" : "Blablabla2", "count" : 1 }
    > 
    
相关问题