根据您提供的信息,我会推荐两种可能的方法,从相同的基础开始:
使用两个集合(文章和平台),并仅将平台文档的引用存储在文章定义的数组中
文件
如果出现以下情况,我会推荐这种方法:
- 您的两个文章文档的基数都很高,并且
平台
-
您希望能够独立管理两个实体,同时
还同步它们之间的引用
// articles collection schema
{
"_id": ...,
"title": "I am an article",
...
"platforms": [ "platform_1", "platform_2", "platform_3" ],
...
}
// platforms collection schema
{
"_id": "platform_1",
"name": "Platform 1",
"url": "http://right/here",
...
},
{
"_id": "platform_2",
"name": "Platform 2",
"url": "http://right/here",
...
},
{
"_id": "platform_3",
"name": "Platform 3",
"url": "http://right/here",
...
}
即使这种方法非常灵活,它也是有代价的 - 如果您同时需要文章和平台数据,您将不得不向 MongoDB 实例发起更多查询,因为数据被分成两个不同的集合。
例如,在加载文章页面时,考虑到您还想显示列表platforms
,你必须向articles collection
,然后还触发搜索platforms collection
通过成员检索该文章发布到的所有平台实体platform
s 数组上article document
.
但是,如果您只有一小部分经常访问的platform attributes
加载时您需要提供article document
,你可能会增强platforms
数组上的articles collection
除了存储这些属性_id
平台文档参考:
// enhanced articles collection schema
{
"_id": ...,
"title": "I am an article",
...
"platforms": [
{platform_id: "platform_1", name: "Platform 1"},
{platform_id: "platform_2", name: "Platform 2"},
{platform_id: "platform_3", name: "Platform 3"}
],
...
}
如果以下情况,这种混合方法将是合适的:platform data attributes
您经常检索并与文章特定数据一起显示的数据不会经常更改。
否则,您将必须同步对platform document attributes
in the platforms collection
包含您作为文章文档平台数组的一部分进行跟踪的属性子集。
关于各个平台的文章列表的管理,我不建议在两个集合中存储 N 到 N 的引用,因为前面提到的机制已经允许您通过查询来提取文章列表。articles collection
使用查找查询_id
的值platform document
:
Approach #1
db.articles.find({"platforms": "platform_1"});
Approach #2:
db.articles.find({"platforms.platform_id": "platform_1"});
在介绍了两种不同的方法之后,我现在建议您分析应用程序的查询模式和性能阈值,并根据您遇到的场景做出经过计算的决策。