MongoDB基于数组元素关联查询 将user集合following数组ID替换为对应用户名
你可以通过MongoDB聚合框架实现该需求,核心使用$lookup关联同集合的用户数据,具体查询语句如下:
db.user.aggregate([ // 筛选指定用户,示例中为_id是70c7ad56ea3ef6002f76df7b的用户,可根据需求调整匹配条件 { $match: { _id: ObjectId("70c7ad56ea3ef6002f76df7b") } }, // 关联user集合,将following数组内的_id替换为对应用户的完整文档 { $lookup: { from: "user", localField: "following", foreignField: "_id", as: "following" } }, // 可选步骤:仅保留following数组中的_id和username字段,过滤多余字段 { $project: { username: 1, following: { $map: { input: "$following", as: "item", in: { _id: "$$item._id", username: "$$item.username" } } } } } ])
如果不需要过滤following的冗余字段,直接去掉最后一步的$project阶段即可,$lookup返回的结果本身就已经是包含用户全字段的对象数组,符合你要求的结构。
内容的提问来源于stack exchange,提问作者Chitova263
相关产品推荐
相关产品推荐

