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

查看:29
本文介绍了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

因为 John 在 session=1 组中年龄最大,而 Tommy 在 session=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.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

您可以尝试以下使用 max 属性的聚合查询:http://docs.mongodb.org/manual/reference/operator/aggregation/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天全站免登陆