Mongoose聚合查询:筛选特定用户关注列表中存在video字段的用户
解决方案
实现逻辑
你只需要在$lookup的子查询pipeline中,新增针对video字段的过滤条件即可,过滤规则需要同时满足两点:
video字段真实存在video字段的值不为null(避免字段存在但为空值的情况被误判)
完整可运行代码
const user = await User.aggregate([ // 匹配指定的目标用户 { $match: { _id: ObjectId(user_id) } }, { $lookup: { from: "users", let: { following: "$following" }, pipeline: [ { $match: { $expr: { $in: ["$_id", "$$following"] }, // 新增video字段的过滤条件 video: { $exists: true, $ne: null } } }, // 可选配置:如果不需要返回被关注用户的全部字段,可以在这里用$project裁剪冗余字段 // { $project: { password: 0, createTime: 0 } } ], as: "following", }, }, // 可选配置:如果只需要关注列表不需要原用户其他信息,可以加这个配置直接取出结果 // { $project: { following: 1, _id: 0 } } ]); const followed_users = user[0].following;
可选优化写法
如果你不需要保留原用户的其他属性,还有更简洁的写法,直接拆分关注列表后过滤:
const followed_users = await User.aggregate([ { $match: { _id: ObjectId(user_id) } }, { $unwind: "$following" }, { $lookup: { from: "users", localField: "following", foreignField: "_id", as: "followedUser" } }, { $unwind: "$followedUser" }, { $match: { "followedUser.video": { $exists: true, $ne: null } } }, { $replaceRoot: { newRoot: "$followedUser" } } ]);
内容的提问来源于stack exchange,提问作者AG_HIHI
相关产品推荐
相关产品推荐

