在多个集合上实现联接

时间:2019-04-24 05:47:07

标签: node.js mongodb performance mongoose social-networking

我正在尝试创建一个社交网络应用程序,该应用程序可以具有连接(关注者,关注者),帖子,评论,喜欢,分享等。这是一个MVP项目,但我仍然想针对此用例探索mongoDB。我对此应用程序的性能有疑问。

我有三个收藏夹:

  • 帖子:应在此处添加新帖子。该集合包含与帖子相关的所有详细信息。

    Schema: const postSchema = new mongoose.Schema({ user_id: String, title: String, text: String, type: { type: String, enum: ["music", "movie", "tv"] }, mediaUrl: String, thumbnailUrl: String, accessType: { type: Number, enum: [1, 2, 3] }, tags: [String], like_count: Number, comment_count: Number, share_count: Number, insertDate: { type: Date, default: () => { return new Date(); } } });

  • Feeds:此集合仅添加用户和发布的元数据,包括标签。我打算用它来获取特定用户的相关提要。

    Schema: const feedSchema = new mongoose.Schema({ post_id: String, user_id: String, isTag: Boolean, isPublic: Boolean, insertDate: { type: Date, default: () => { return new Date(); } }, modifiedDate: { type: Date, default: () => { return new Date(); } } });

  • 连接:此集合用于用户关系。

    Schema: const connectSchema = new mongoose.Schema({ followed_by: String, user_id: String, insertDate: { type: Date, default: () => { return new Date(); } } });

我的方法是先从我关注的订阅源收集用户那里找到帖子,然后从帖子收集中获取帖子。 这是我尝试的查询:

db.connects.aggregate([
    { $match: { followed_by: "5cbefd61d3b53a4aaa9a2b16" } },
    {
      $lookup: {
        from: "feeds",
        let: { user_id: "$user_id" },
        pipeline: [{ $match: { $expr: { $or: [{ $eq: ["$user_id", "$$user_id"] }, { isPublic: true }] } } }],
        as: "feedData"
      }
    },
    { $unwind: "$feedData" },
    { $replaceRoot: { newRoot: "$feedData" } },
    { $group: { _id: { post_id: { $toObjectId: "$post_id" }, modifiedDate: { $toLong: "$modifiedDate" } } } },
    { $replaceRoot: { newRoot: "$_id" } },
    { $sort: { modifiedDate: -1 } },
    { $skip: 0 },
    { $limit: 10 },
    {
      $lookup: { from: "posts", localField: "post_id", foreignField: "_id", as: "postData" }
    },
    { $unwind: "$postData" },
    { $replaceRoot: { newRoot: "$postData" } },
    { $addFields: { userId: { $toObjectId: "$user_id" } } },
    {
      $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "userData" }
    },
    {
      $project: {
        post_id: "$_id",
        user_id: 1,
        title: 1,
        text: 1,
        typeaccessType: 1,
        mediaUrl: 1,
        thumbnailUrl: 1,
        insertDate: { $toLong: "$insertDate" },
        like_count: 1,
        comment_count: 1,
        share_count: 1,
        user_email: { $arrayElemAt: ["$userData.email", 0] },
        user_profile_pic: { $arrayElemAt: ["$userData.profile_pic", 0] },
        username: { $arrayElemAt: ["$userData.firstname", 0] }
      }
    }
  ]).pretty();

请分享您对以下问题的反馈:

  1. 我应该使用哪个索引来提高性能?
  2. 在mongoDB中是否有更好的方法可以做到这一点。另外,是否可以优化查询的任何部分?

0 个答案:

没有答案