2017-10-17 123 views
0

这是我的友人收藏如何获得朋友的排行榜MongoDB中

[ 
    { 
     "_id": "59e4fbcac23f38cdfa6963a8", 
     "friend_id": "59e48f0af8c277d7a8886ed7", 
     "user_id": "59e1d36ad17ad5ad3d0453f7", 
     "__v": 0, 
     "created_at": "2017-10-16T18:34:50.875Z" 
    }, 
    { 
     "_id": "59e5065f705a90cfa218c9e5", 
     "friend_id": "59e48f0af8c277d7a8886edd", 
     "user_id": "59e1d36ad17ad5ad3d0453f7", 
     "__v": 0, 
     "created_at": "2017-10-16T19:19:59.483Z" 
    } 
] 

这是我的分数集合:

[ 
    { 
     "_id": "59e48f0af8c277d7a8886ed8", 
     "score": 19, 
     "user_id": "59e48f0af8c277d7a8886ed7", 
     "created_at": "2017-10-13T09:02:10.010Z" 
    }, 
    { 
     "_id": "59e48f0af8c277d7a8886ed9", 
     "score": 24, 
     "user_id": "59e48f0af8c277d7a8886ed7", 
     "created_at": "2017-10-11T00:56:10.010Z" 
    }, 
    { 
     "_id": "59e48f0af8c277d7a8886eda", 
     "score": 52, 
     "user_id": "59e48f0af8c277d7a8886ed7", 
     "created_at": "2017-10-24T09:16:10.010Z" 
    }, 
] 

这是我的用户集合。

[ 
    { 
     "_id": "59e48f0af8c277d7a8886ed7", 
     "name": "testuser_0", 
     "thumbnail": "path_0" 
    }, 
    { 
     "_id": "59e48f0af8c277d7a8886edd", 
     "name": "testuser_1", 
     "thumbnail": "path_1" 
    }, 
    { 
     "_id": "59e48f0af8c277d7a8886ee3", 
     "name": "testuser_2", 
     "thumbnail": "path_2" 
    }, 
    { 
     "_id": "59e48f0af8c277d7a8886ee9", 
     "name": "testuser_3", 
     "thumbnail": "path_3" 
    }, 
] 

,最后我需要的朋友高分排序为特定的时间周期名单(说过去24小时内),像这样的东西......

[ 
{ 
"friend_id": "59e48f0af8c277d7a8886ed7", 
"friend_name":"test_user_2" 
"thumbnail":"image_path", 
"highscore":15 
}, 
"friend_id": "59e48f0af8c277d7a8886edd", 
"friend_name":"test_user_3" 
"thumbnail":"image_path", 
"highscore":10 
} 
] 

什么是实现这一目标的最佳途径?我已经尝试了聚合管道,但对3个集合的工作感到困惑。

+0

收集的方式看起来很像SQL表设计。有理由吗? 用户可以将朋友列表和分数列表全部嵌入同一文档中。 另外,MongoDB不像SQL那样很棒。 –

+0

@ A.P。评分将随着时间的推移不断增加。用户每天将有20-30条评分。在朋友的情况下,它可以被嵌入,但是100-500个条目的数组大小不会太大并且影响性能? –

回答

0

根据您的回答,文档中500个条目的数组大小对于存储朋友可能不是一个坏主意,因为您只会在每个条目中存储“friends id”和“created”。它节省了一个集合。 如果您仅通过选择所需字段来投影查询中的数据,则不会出现太多性能问题。

https://docs.mongodb.com/v3.2/tutorial/project-fields-from-query-results/#return-specified-fields-only

对于得分的30每天这种增加;它取决于你做什么类型的查询。 通过每天添加30个分数,每个文档达到2MB限制需要一段时间。

关于加入不同的收藏有一个关于它的堆栈溢出问题:

How do I perform the SQL Join equivalent in MongoDB?

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

您将需要使用聚合框架从MongoDB的使用,如果;不只是一个查找命令。

+0

我使用查找聚合工作。我目前的查询时间大约为400ms,可以在过去24小时内获得朋友的排行榜,当时我拥有10,000个用户和100,000个分数条目。 不知道以什么速度它会增加我想我应该尝试阵列方式以及比较。 –

+0

长椅标记不同的收藏设计总是一个好主意。 –