如何聚合集合中的嵌套字段?

时间:2021-02-09 17:35:15

标签: mongodb mongoose

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

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",
      },
    },
  ]);

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

1 个答案:

答案 0 :(得分:0)

感谢@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" },
      },
    },
  ]);