根据您提供的信息,我会推荐两种可能的方法,从相同的基础开始:
使用两个集合(文章和平台)并仅将平台文档的引用存储在文章上定义的数组中
文件
如果出现以下情况,我会推荐这种方法:
- 您的文章文档和文章文档的基数都很高
平台
-
您希望能够独立管理这两个实体,同时
还同步它们之间的引用
// 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 的搜索通过article document 上的platforms 数组的成员检索该文章发布到的所有平台实体。
但是,如果在加载article document 时只有一小部分经常访问的platform attributes 可用,则可以增强articles collection 上的platforms 数组以另外存储这些属性对_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 不经常更改,则这种混合方法将是合适的。
否则,您必须将对 platforms collection 中的 platform document attributes 所做的所有更新与作为文章文档平台数组的一部分跟踪的属性子集同步。
关于单个平台的文章列表管理,我不建议在两个集合中存储 N 对 N 引用,因为上述机制已经允许您通过使用查找查询查询 articles collection 来提取文章列表使用platform document 的_id 值:
Approach #1
db.articles.find({"platforms": "platform_1"});
Approach #2:
db.articles.find({"platforms.platform_id": "platform_1"});
在介绍了两种不同的方法之后,我现在建议您分析应用程序的查询模式和性能阈值,并根据您遇到的场景做出计算决策。