将这些数据存储在 mongoDB 上的最佳数据结构是什么? [英] What is the best data structure to store this data on mongoDB?

查看:68
本文介绍了将这些数据存储在 mongoDB 上的最佳数据结构是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个新闻发布网站.我想让我的用户选择他们最喜欢的新闻并将它们存储在列表中.任何时候用户想要显示他的收藏夹,新闻都应该按日期排序并显示.

I'm designing a news publishing website. I want to allow my users to pick their favorite news and store them in a list. Any time a user wants to show his favorites, the news should be sorted by date and shown.

目前要存储的结构是这样的:

The structure to store is currently like this:

favorite_table = 
{
    user_id,
    data
}

所有新闻都存储在数据字段中,如下所示:

All news are stored in the data field like this:

[{date:news_id},{date:news_id},{date:news_id]  

既然所有的值都是按日期排序的,那么它是一个很好的存储新闻的结构吗?我必须在数据到达时附加数据.我的结构适合我的目的还是有更好的结构?

Since all values are sorted by date, is it a good structure to store news? I have to append data whenever it arrives. Is my structure suitable for my purpose or is there a better structure?

推荐答案

您的结构看起来正确.您只在数据字段中存储 news_id ,这是一个更智能的实现,因为每次用户将新新闻添加到收藏夹时,存储完整文档都会导致 MongoDB 进行大量移动和写入.

Your structure looks correct. You are storing only news_id in the data field and that's a smarter implementation because storing complete document will cause a lot of moving and writing by MongoDB every time a new news is added to favorites by the user.

您可能已经知道的原因是每次更新时都会创建一个新文档.参考:http://docs.mongodb.org/manual/参考/方法/db.collection.save/#upsert.

Reason, which you probably already know, is that a new document is created on every update. Reference: http://docs.mongodb.org/manual/reference/method/db.collection.save/#upsert.

此外,我认为作为业务规则,您应该限制用户可以设置为最喜欢的新闻项目的数量.允许这个列表无限增长对于嵌入式设计来说不是一个好主意.

Also i think that as a business rule you should restrict the number of news items that can be set as favorite by the user. Allowing this list to grow indefinitely will not be a good idea for the embedded design.

如果您想要无限数量的收藏夹,您最好为此创建一个单独的集合,然后要获取用户的所有收藏夹,请使用 $match(在用户的 id 上)和 $sort(新闻项目)运算符聚合查询以获取用户最喜欢的新闻项目的排序列表.

In case you want an unlimited number of favorites, you better create a separate collection for that and then to get all the favorites by a user use $match (on user's id) and $sort (of news items) operators in an aggregation query to get the sorted list of favorite news items for the user.

这篇关于将这些数据存储在 mongoDB 上的最佳数据结构是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆