You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB聚合阶段后按条件限制返回结果

问题根因
  • 现有聚合逻辑仅在$lookup关联用户集合时校验了用户的hookups状态为true,但没有在关联完成后过滤关联结果为空的Swipe文档
  • 你为$unwind配置了preserveNullAndEmptyArrays: true,就算关联不到符合条件的用户,对应的Swipe文档也不会被剔除,仍会保留在结果集中
  • 你修改某用户的hookups状态为false后,涉及该用户的Swipe文档关联后userone/usertwo字段为空,但未被过滤,因此多出来了仅包含user_two的无效条目
修复方案

在两个$unwind阶段之后、$sort阶段之前,新增一个$match阶段,过滤掉对方用户未通过hookups校验的无效记录即可。

修改后的完整代码如下:

const fetchHookups = (req, res, next) => {
  const currentUserId = ObjectId(req.body._id)
  const query = {
    $or: [
      { user_one: currentUserId },
      { user_two: currentUserId },
    ]
  }
    
  Swipe.aggregate([
    { $match: query },
    {
      $lookup: {
        from: 'users',
        let: { user_one: '$user_one', hookupstatus: true },
        pipeline: [{
          $match: {
            $expr: {
              $and: [
                { $eq: ["$_id", "$$user_one"] },
                { $eq: ["$hookups", "$$hookupstatus"] },
              ],
            }
          }
        }],
        as: "userone"
      }
    },
    {
      $unwind: {
        path: "$userone",
        preserveNullAndEmptyArrays: true,
      },
    },
    {
      $lookup: {
        from: 'users',
        let: { user_two: '$user_two', hookupstatus: true },
        pipeline: [{
          $match: {
            $expr: {
              $and: [
                { $eq: ["$_id", "$$user_two"] },
                { $eq: ["$hookups", "$$hookupstatus"] },
              ],
            }
          }
        }],
        as: "usertwo"
      }
    },
    {
      $unwind: {
        path: "$usertwo",
        preserveNullAndEmptyArrays: true,
      },
    },
    // 新增过滤阶段
    {
      $match: {
        $or: [
          // 当前用户为user_one时,对方usertwo必须符合hookups要求
          { $and: [ { user_one: currentUserId }, { usertwo: { $exists: true, $ne: null } } ] },
          // 当前用户为user_two时,对方userone必须符合hookups要求
          { $and: [ { user_two: currentUserId }, { userone: { $exists: true, $ne: null } } ] }
        ]
      }
    },
    {
      $sort: {
        _id: -1
      }
    }
  ]).exec(function(error, response) {
    if (error) {
      console.log(error)
    } else {
      res.json(response)
    }
  })
}

内容的提问来源于stack exchange,提问作者Lexacle Technologies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:57:01