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

3
我的文档集合中的文档结构如下:
    [

    {
    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个回答

1

你能尝试这个聚合吗?

  1. $sort - 按日期排序,以便在 $group 中获取 $last 元素
  2. $group - 按 $cond _id 分组,并按字母顺序使用 $concat 进行合并
  3. $sort - 按升序对结果进行 _id 排序

管道

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 }
> 

2
这就是我想表达的意思。你真是个天才。谢谢。 - nelkor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接