MongoDB跨多集合查询怎么获取符合条件的员工关联文件位置?
你的场景完全可以用聚合操作的$lookup实现,查询语句如下,直接在Studio3T的employees集合运行该聚合即可得到目标结果:
db.employees.aggregate([ // 筛选符合filesAccess.web为true的员工数据 { $match: { "filesAccess.web": true } }, // 提取fileIds数组的第一个元素作为关联查询的匹配键 { $addFields: { firstFileId: { $arrayElemAt: ["$fileIds", 0] } } }, // 关联files集合匹配对应文件信息 { $lookup: { from: "files", localField: "firstFileId", foreignField: "_id", as: "fileInfo" } }, // 展开关联返回的单元素数组,简化后续字段取值 { $unwind: "$fileInfo" }, // 格式化返回结果,仅保留需要的字段 { $project: { _id: 1, name: 1, location: "$fileInfo.fileMetaData.location" } } ])
如果需要兼容fileIds为空的极端场景,可以在$match阶段额外添加fileIds: {$exists: true, $ne: []}过滤条件,避免后续步骤出错。
内容的提问来源于stack exchange,提问作者Cineno28
相关产品推荐
相关产品推荐

