MongoDB-获取集合中每个组具有最大属性的文档 [英] MongoDB - get documents with max attribute per group in a collection

查看:66
本文介绍了MongoDB-获取集合中每个组具有最大属性的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下:

session, age, firstName, lastName
1, 28, John, Doe
1, 21, Donna, Keren
2, 32, Jenna, Haze
2, 52, Tommy, Lee
..
..

我想获取每个会话中最大的(按年龄)的所有行.因此,对于上述输入,我的输出将如下所示:

I'd like to get all the rows which are the largest (by age) per session. So So for the above input my output would look like:

sessionid, age, firstName, lastName
1, 28, John, Doe
2, 52, Tommy, Lee

因为约翰在会话= 1组中年龄最大,而汤米在会话= 2组中年龄最大.

because John has the largest age in the session = 1 group and Tommy has the largest age on the session=2 group.

我需要将结果导出到文件(csv),并且其中可能包含很多记录.

I need to export the result to a file (csv) and it may contain lots of records.

我该如何实现?

推荐答案

您可以尝试以下使用max属性的聚合查询:

You could try the below aggregation query which uses max attribute: http://docs.mongodb.org/manual/reference/operator/aggregation/max/

db.collection.aggregate([
   $group: {
       "_id": "$session",           
       "age": { $max: "$age" }
     },
   { $out : "max_age" }
])

应该将结果输出到新的集合max_age中,然后可以将其转储到csv中.

The results should be outputted to the new collection max_age and then you could dump it into a csv.

注意:它将仅提供会话和最大年龄,而不会返回其他字段.

Note: it will give only the session and max age and will not return other fields.

这篇关于MongoDB-获取集合中每个组具有最大属性的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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