MongoDB多$lookup依赖首次查询结果获取用户与代表数据返回空数组问题
问题原因
你遇到的空返回问题是由$unwind的默认行为导致的:
- 不带参数的
$unwind会自动过滤掉目标字段为空数组/不存在的整条文档 - 因为你的payments集合中
userId和representativeId互斥存在,所以两次$lookup执行完成后,representative和user两个数组必然有一个为空,连续两次无参数$unwind会把所有记录全部过滤,最终返回空数组。
修复方案
给两个$unwind配置preserveNullAndEmptyArrays: true参数,允许空数组对应的记录保留,修改后的聚合语句如下:
const userAndRepData = await ChequeDB.aggregate<{[key: string]: any}>([ { $match: { $and: [ { 'chequeNumber': { $in: chequeData.map(c => c.chequeNumber) }, 'accountNumber': { $in: chequeData.map(c => c.accountNumber) } } ] } }, { $lookup: { from: 'payments', localField: 'paymentId', foreignField: '_id', as: 'payment' } }, { $unwind:'$payment' }, { $lookup: { from: 'representatives', localField: 'payment.representativeId', foreignField: '_id', as: 'representative' } }, // 新增参数,保留representative为空数组的记录 { $unwind: { path: '$representative', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'users', localField: 'payment.userId', foreignField: '_id', as: 'user' } }, // 新增参数,保留user为空数组的记录 { $unwind: { path: '$user', preserveNullAndEmptyArrays: true } }, { $project: { user: 1, _id: 0, representative: 1 } } ]);
可选优化(按需使用)
如果你希望把两类数据合并到同一个字段返回,避免空值,可以在$project前新增如下阶段:
{ $addFields: { // 互斥字段自动取有值的那个作为最终身份信息 identity: { $ifNull: ['$user', '$representative'] } } }
之后在$project配置中加入identity:1即可。
内容的提问来源于stack exchange,提问作者Guy 235
相关产品推荐
相关产品推荐

