You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:50:44