按一个字段进行汇总,然后选择具有另一个字段最大值的文档作为集合 [英] Aggregating by a field and selecting the document with the max value of another field as a collection

查看:64
本文介绍了按一个字段进行汇总,然后选择具有另一个字段最大值的文档作为集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用聚合框架,什么是获取每个分组中字段最大值的文档的最佳方法,因此使用下面的集合,我希望具有为每个具有最新日期的group_id返回一个文档的功能.第二个清单显示了预期的结果.

Using the aggregate framework, what is the best way to get documents with a maximum value of a field per grouping so using the collection below I would like to have functionality to return one document for each group_id having the latest date. The second listing shows the desired result.

group_id date 
1        11/1/12  
1        11/2/12
1        11/3/12
2        11/1/12
3        11/2/12
3        11/3/12

期望结果

group_id date
1        11/3/12
2        11/1/12
3        11/3/12

推荐答案

您可以使用 $max 聚合框架中的分组功能,以查找每个group_id的最新文档.您将需要其他查询才能根据分组的条件检索完整的文档.

You can use the $max grouping function in the Aggregation Framework to find the latest document for each group_id. You will need additional queries to retrieve the full documents based on the grouped criteria.

var results = new Array();
db.groups.aggregate(
    // Find documents with latest date for each group_id
    { $group: {
        _id: '$group_id',
        date: { $max: '$date' },
    }},
    // Rename _id to group_id, so can use as find criteria
    { $project: {
        _id: 0,
        group_id:'$_id',
        date: '$date'
    }}
).result.forEach(function(match) {
    // Find matching documents per group and push onto results array
    results.push(db.groups.findOne(match));
});

示例结果:

{
    "_id" : ObjectId("5096cfb8c24a6fd1a8b68551"),
    "group_id" : 1,
    "date" : ISODate("2012-11-03T00:00:00Z"),
    "foo" : "bar"
}
{
    "_id" : ObjectId("5096cfccc24a6fd1a8b68552"),
    "group_id" : 2,
    "date" : ISODate("2012-11-01T00:00:00Z"),
    "foo" : "baz"
}
{
    "_id" : ObjectId("5096cfddc24a6fd1a8b68553"),
    "group_id" : 3,
    "date" : ISODate("2012-11-03T00:00:00Z"),
    "foo" : "bat"
}

这篇关于按一个字段进行汇总,然后选择具有另一个字段最大值的文档作为集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆