MongoDB聚合:匹配数组对象字段并实现结果重组与大小写不敏感查询
解决方案
以下是满足需求的完整MongoDB聚合查询,同时解决大小写不敏感匹配和结果结构重组两个核心问题:
db.Collaborators.aggregate([ // 可选:如果仅需查询特定邮箱用户,可在此添加过滤条件 // { $match: { email: { $regex: /me@me.com/i } } }, { $lookup: { from: "Initiatives", let: { userEmail: "$email" }, pipeline: [ // 第一步:筛选包含目标邮箱(大小写不敏感)的项目文档 { $match: { $expr: { $in: [ { $toLower: "$$userEmail" }, { $map: { input: "$Collaborators", as: "collab", in: { $toLower: "$$collab.email" } } } ] } } }, // 展开Collaborators数组,便于精准筛选当前用户的条目 { $unwind: "$Collaborators" }, // 第二步:精准匹配当前用户的协作条目(大小写不敏感) { $match: { $expr: { $eq: [ { $toLower: "$Collaborators.email" }, { $toLower: "$$userEmail" } ] } } }, // 重组结构:提取所需字段,将role、rating与title合并为目标格式 { $project: { _id: 0, title: 1, role: "$Collaborators.role", rating: "$Collaborators.rating" } } ], as: "Initiatives" } }, // 可选:过滤掉未参与任何项目的用户 { $match: { Initiatives: { $ne: [] } } } ])
关键细节说明
大小写不敏感匹配:
通过$toLower将用户邮箱和项目协作人邮箱统一转换为小写后再比较,完全兼容ME@ME.COM、Me@Me.Com这类大小写变体。第一个$match阶段先用$map把项目的所有协作人邮箱转成小写数组,再用$in判断用户邮箱是否在其中,避免提前展开数组造成性能浪费。结果结构重组:
在$lookup的内部管道最后添加$project阶段,直接提取项目title,并将协作人对象中的role、rating字段提升到顶层,同时排除不需要的_id,最终Initiatives数组的元素完全符合目标结构。性能优化:
先通过第一个$match过滤出包含目标用户的项目文档,再执行$unwind操作,比直接展开所有项目数组后筛选更高效,尤其适合数据量较大的集合。
内容的提问来源于stack exchange,提问作者richnwilson
相关产品推荐
相关产品推荐

