MongoDB:关联表无匹配记录时如何将关联字段设为null
解决MongoDB聚合中无匹配记录时字段显示null的问题
要让无匹配user_tasks的记录中cur_task_status、started_at、completed_at字段显示为null,只需在$project阶段使用$ifNull操作符,为每个字段指定默认值即可。
当user_tasks中无匹配项时,$unwind后的started字段为null,直接引用$started.status这类子字段会导致整个字段被省略。而$ifNull可以在目标值不存在时返回指定的默认值(这里设为null),确保字段始终存在。
修改后的关键$project阶段
{ '$project': { 'name': 1, 'type': 1, 'cur_task_status': { $ifNull: ['$started.status', null] }, 'completed_at': { $ifNull: ['$started.completed_at', null] }, 'started_at': { $ifNull: ['$started.started_at', null] }, 'experience': 1, 'points': 1 // 补充原结果中存在的points字段 } }
完整聚合管道
[ { '$match': { 'topic_id': new ObjectId('....'), 'status': 'active' } }, { '$lookup': { 'from': 'user_tasks', 'localField': '_id', 'foreignField': 'task_id', 'as': 'started', 'pipeline': [ { '$match': { 'user_id': new ObjectId('....') } } ] } }, { '$unwind': { 'path': '$started', 'preserveNullAndEmptyArrays': true } }, { '$project': { 'name': 1, 'type': 1, 'cur_task_status': { $ifNull: ['$started.status', null] }, 'completed_at': { $ifNull: ['$started.completed_at', null] }, 'started_at': { $ifNull: ['$started.started_at', null] }, 'experience': 1, 'points': 1 } } ]
处理后,即使没有匹配的user_tasks记录,这三个字段也会明确显示为null,不会缺失。
内容的提问来源于stack exchange,提问作者Anil kumar
相关产品推荐
相关产品推荐

