如何通过insertedId获取MongoDB中authors集合的文档?
通过books集合中的insertedId获取对应作者文档的方法
你的books集合文档里,author字段包含了authors集合中文档的insertedId,要获取对应的作者文档,有两种实用方法:
方法一:分步查询
先从books集合中提取目标作者的insertedId,再用这个ID查询authors集合:
// 1. 找到目标书籍,提取author.insertedId const targetBook = db.books.findOne({ name: 'the teacher' }); const targetAuthorId = targetBook.author.insertedId; // 2. 用ID查询authors集合 const targetAuthor = db.authors.findOne({ _id: targetAuthorId }); printjson(targetAuthor);
方法二:聚合查询(一次性关联)
使用MongoDB的$lookup聚合阶段,直接关联两个集合并返回结果:
db.books.aggregate([ // 匹配你需要查询的书籍 { $match: { name: 'the teacher' } }, // 关联authors集合,通过insertedId匹配作者的_id { $lookup: { from: 'authors', // 要关联的集合名 localField: 'author.insertedId', // books集合中用于匹配的字段 foreignField: '_id', // authors集合中对应的匹配字段 as: 'authorDetails' // 存储匹配结果的字段名(返回数组) } }, // 可选:将结果数组展开为单个对象(方便直接访问) { $unwind: '$authorDetails' } ])
执行后,结果会包含原书籍信息以及匹配到的authorDetails字段,里面就是对应的作者文档。
内容的提问来源于stack exchange,提问作者YSH
相关产品推荐
相关产品推荐

