首页 > 解决方案 > 如何聚合集合中的嵌套字段?

问题描述

我正在创建一个论坛,结构是:

forum -> threads -> thread has a user

我想聚合它而不是填充,我当前的代码是:

const forums = await Forum.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(req.params.id),
      },
    },
    {
      $lookup: {
        from: "threads",
        localField: "_id",
        foreignField: "forumId",
        as: "threads",
      },
    },
    {
      $lookup: {
        from: "users",
        localField: "threads.user",
        foreignField: "_id",
        as: "threads.user",
      },
    },
  ]);

但返回的线程对象有一个用户数组,它会覆盖所有其他线程值。我还希望用户成为一个对象,而不是只有一个用户的数组。我怎么做?

标签: mongodbmongoose

解决方案


感谢@turivishal,我想通了

代码是:

 const forums = await Forum.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(req.params.id),
      },
    },
    {
      $lookup: {
        from: "threads",
        localField: "_id",
        foreignField: "forumId",
        as: "threads",
      },
    },
    {
      $unwind: "$threads",
    },
    {
      $lookup: {
        from: "users",
        localField: "threads.user",
        foreignField: "_id",
        as: "threads.user",
      },
    },
    {
      $unwind: "$threads.user",
    },
    {
      $group: {
        _id: "$_id",
        name: { $first: "$name" },
        threads: { $push: "$threads" },
      },
    },
  ]);


推荐阅读