MongoDB聚合$project阶段获取$birth_date返回空值问题求助
问题原因
$lookup 关联查询返回的 as 字段(此处为user)默认是数组类型,哪怕只匹配到1条用户数据,结果也会被包裹在数组中:
- 直接写
$birth_date是在当前likes集合的文档上查找字段,该集合无此字段,自然返回null - 未拆分数组直接读取
$user.birth_date,拿到的是所有数组元素的birth_date组成的新数组,不符合$dateDiff要求的单个日期类型参数,因此计算返回空
解决方案
在$lookup阶段之后新增一步,将user数组转换为单个对象即可,推荐两种实现方式:
方案1:使用$first取数组首元素(适用于MongoDB 4.4及以上版本)
修改后的完整聚合语句如下:
return await likes.aggregate([ { $lookup: { from: "users", localField: "sender", foreignField: "_id", as: "user" } }, // 新增阶段:把user数组转成单个对象 { $set: { user: { $first: "$user" } } }, { $match: { sending: database.Types.ObjectId(id), status: true } }, { $project: { user: { name: true, age: { $dateDiff: { startDate: "$user.birth_date", endDate: "$$NOW", unit: "year" } }, photo: { first: true, second: true, third: true }, about: true }, create_date: true } } ])
方案2:使用$unwind拆分数组(适用于所有MongoDB版本)
如果你的MongoDB版本低于4.4,将上述新增的$set阶段替换为$unwind即可:
{ $unwind: "$user" }
内容的提问来源于stack exchange,提问作者Önver
相关产品推荐
相关产品推荐

