MongoDB如何单次请求获取controle集合关联的完整帖子数据?
MongoDB关联查询:将controle集合posts数组替换为完整帖子信息
你可以通过MongoDB的聚合框架实现单次查询,利用$lookup阶段关联posts集合,将controle文档中posts数组的_id替换为对应的帖子详情。
具体查询语句
db.controle.aggregate([ { $lookup: { from: "posts", let: { postIds: "$posts" }, pipeline: [ { $match: { $expr: { $in: ["$_id", "$$postIds"] } } }, { $project: { title: 1, img: 1, desription: 1, _id: 0 } } ], as: "posts" } } ])
语句说明
$lookup:指定关联的集合为posts,通过let定义变量postIds存储当前controle文档的posts数组。- 内部
pipeline:$match:匹配posts集合中_id存在于postIds数组中的文档。$project:仅保留需要的title、img、desription字段(注意示例中字段拼写为desription,若实际为description请调整),排除_id。
as: "posts":将关联查询结果覆盖原controle文档中的posts字段。
返回结果示例
执行后,controle文档的posts字段会替换为包含帖子详情的数组:
{ "_id": ObjectId("6332e99e5140f74b61c43e5d"), "title": "Strict", "posts": [ { "title": "SF", "img": "https://media.sss.com/1.png", "desription": "This is the second post" }, // 其他匹配的帖子详情 ], "type": "horizontal" }
内容的提问来源于stack exchange,提问作者sodmin
相关产品推荐
相关产品推荐

