我的收藏中的文件结构如下:
[
{
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
}
]
怎么做?我不知道如何分组两个不同的领域..
答案 0 :(得分:1)
你可以尝试这种聚合
$sort
- 按日期排序以获取$last
$group
元素
$group
- 按字母顺序按$cond
_id和$concat
进行分组$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 }
>