Mongodb:从每个组中选择前N行 [英] Mongodb: Select the top N rows from each group
问题描述
我将mongodb用于我的博客平台,用户可以在其中创建自己的博客.所有博客的所有条目都在一个条目集合中.条目的文档如下:
I use mongodb for my blog platform, where users can create their own blogs. All entries from all blogs are in an entries collection. The document of an entry looks like:
{
'blog_id':xxx,
'timestamp':xxx,
'title':xxx,
'content':xxx
}
正如问题所述,是否有任何方法可以为每个博客选择最后3个条目?
As the question says, is there any way to select, say, last 3 entries for each blog?
推荐答案
在基本的mongo中,如果您可以同时忍受两件事,那么这样做的唯一方法是:
The only way to do this in basic mongo if you can live with two things :
- 您的进入文档中的另一个字段,我们称其为年龄"
- 新博客条目进行了其他更新
如果是,请按照以下步骤操作:
If so, here's how you do it :
-
创建新的简介后,请进行常规插入,然后执行此更新以增加所有帖子(包括您刚刚为此博客插入的帖子)的使用期限:
Upon creating a new intro do your normal insert and then execute this update to increase the age of all posts (including the one you just inserted for this blog) :
db.entries.update({blog_id:BLOG_ID},{age:{$ inc:1}},false,true)
db.entries.update({blog_id: BLOG_ID}, {age:{$inc:1}}, false, true)
查询时,使用以下查询将为每个博客返回最新的3个条目:
When querying, use the following query which will return the most recent 3 entries for each blog :
db.entries.find({age:{$ lte:3},timestamp:{$ gte:STARTOFMONTH,$ lt:ENDOFMONTH}}).sort({blog_id:1,age:1})
db.entries.find({age:{$lte:3}, timestamp:{$gte:STARTOFMONTH, $lt:ENDOFMONTH}}).sort({blog_id:1, age:1})
请注意,此解决方案实际上是并发安全的(没有重复使用期限的条目).
Note that this solution is actually concurrency safe (no entries with duplicate ages).
这篇关于Mongodb:从每个组中选择前N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!