首页 > 解决方案 > 嵌入重复的“友谊”子文档来模拟 MongoDB 中的相互友谊边缘

问题描述

我正在尝试在 MongoDB 中模拟双向友谊。“双向”意味着,像 Facebook 但与 Twitter 不同,如果您是 Sam 的朋友,那么 Sam 也必须是您的朋友。在 MongoDB 中,通常推荐的解决方案(example)似乎是这样的:

我正在考虑一种不同的设计,而不是单独的Friendship集合,边缘数据将存储(复制)在双向关系的两个节点中。像这样:

  {
    _id: new ObjectID("111111111111111111111111"),
    name: "Joe", 
    pictureUrl: "https://foo.com/joe.jpg",
    invites: [
      ... // similar schema to friends array below
    ],
    friends: [
      {
        friendshipId: new ObjectID("123456789012345678901234"),
        lastMeeting: new Date("2019-02-07T20:35:55.256+00:00"),
        user1: {
          userId: new ObjectID("111111111111111111111111"),
          name: "Joe",  // cached, read-only data to avoid multi-doc reads
          pictureUrl: "https://foo.com/joe.jpg",
        },
        user2: {
          userId: new ObjectID("222222222222222222222222"),
          name: "Bill",  // cached, read-only data to avoid multi-doc reads
          pictureUrl: "https://foo.com/bill.jpg",
        },
      }
    ]
  },
  {
    _id: new ObjectID("222222222222222222222222"),
    name: "Bill",
    pictureUrl: "https://foo.com/bill.jpg",
    invites: [
      ... // similar schema to friends array below
    ],
    friends: [
      {
        friendshipId: new ObjectID("123456789012345678901234"),
        lastMeeting: new Date("2019-02-07T20:35:55.256+00:00"), // shared data about the edge
        user1: {  // data specific to each friend
          userId: new ObjectID("111111111111111111111111"),
          name: "Joe",  // cached, read-only data to avoid multi-doc reads
          pictureUrl: "https://foo.com/joe.jpg",
        },
        user2: { // data specific to each friend
          userId: new ObjectID("222222222222222222222222"),
          name: "Bill",  // cached, read-only data to avoid multi-doc reads
          pictureUrl: "https://foo.com/bill.jpg",
        },
      }
    ]
  }

以下是我打算如何处理以下问题:

我有两个基本问题希望得到您的建议:

顺便说一句,我知道与 MongoDB 相比,图形数据库甚至关系数据库在建模关系方面做得更好。但是由于各种原因,我现在已经选择了 MongoDB,所以请限制对 MongoDB 解决方案的回答,而不是让我使用图形或关系数据库。谢谢!

标签: mongodbgraph-theorydata-modelingsocial-networking

解决方案


推荐阅读