MongoDB Map-Reduce Find Values from Last Record per User

∥☆過路亽.° 提交于 2019-12-11 13:06:33

问题


I am trying to get some data about the authors of twitter posts, based on the latest data I have

Given a collection of twitter posts, I want to pull information from the latest post per author - ie. I want per author to get the friend count.

Roughly the collection has data like this.

[{"post":
{"post_date": "Sat, 24 Mar 2012 05:52:21 +0000" {"author": {"author_id":123, "friend_count":321}} ,{"post_date": "Sat, 17 Mar 2012 03:22:11 +0000" {"author": {"author_id":123, "friend_count":311}} ,{"post_date": "Sat, 10 Mar 2012 03:22:11 +0000" {"author": {"author_id":123, "friend_count":331}} }}]

I don't want the max of the friend_count but the value from the latest post.

Thanx


回答1:


You don't need to use mapreduce, you can do this with simple aggregation.

Something to the effect of:

db.collection.aggregate(
         {$sort:{post_date:-1}}, 
         {$group:{_id:"$author.author_id", friend_count:{$first:"$author.friend_count"}}}
)

Given the simplified sample data you gave this will $sort it by post_date newest to oldest, so that then when grouping by author_id, the $first record will be one that's the latest.



来源:https://stackoverflow.com/questions/18907038/mongodb-map-reduce-find-values-from-last-record-per-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!