MongoDB通过嵌套数据对文档进行排序 [英] MongoDB sorting documents by nested data
问题描述
考虑以下帖子设计:
{
title: string,
body: string,
comments: [
{name: string, comment: string, ...},
{name: string, comment: string, ...},
...
]
}
...
1)我想选择我收藏中的所有帖子,并按照评论最多的帖子进行排序.我假设由于.length变量始终是通过javascript设置的,因此可以使用它进行排序,但是我不知道将注释计数存储在后文档中的字段中的方式或实际上是否更有效?
1) I would like to select all posts in my collection and have them sorted by the posts that have the most comments. I'm assuming since the .length variable is always set via javascript that it is possible to use this to sort by but I don't know how or if it's actually more efficient to store the comment count in a field in the post document?
1.1)还是将注释计数存储在单独的文档中并不断进行更新更有意义?
1.1) Or does it make more sense to store the comment count in a separate document and continiously update that?
2)选择帖子时,是否可以将结果限制为仅返回帖子文档的最后3条评论,而不是整个数组?
2) When selecting posts, is it possible to limit the result to only return back the last 3 comments of a post document as opposed to the whole array?
推荐答案
您需要使用aggregate
命令
这应该给您一个_id列表,其中注释的数量按相反的顺序按计数进行排序.
This should give you a list of post _id with the number of comments sorted by the count in reverse order.
您可以使用$ limit运算符返回x的前几行.例如{ $limit : 5 }
You can use the $limit operators to return the x top rows. e.g. { $limit : 5 }
db.posts.aggregate(
{ $unwind : "$comments" },
{ $group : { _id : "$_id" , number : { $sum : 1 } } },
{ $sort : { number : -1 } }
);
看看 http://docs.mongodb.org/manual/tutorial/aggregation-examples/
这篇关于MongoDB通过嵌套数据对文档进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!