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

如何在Mongoose中筛选包含指定演员ID的嵌套文档电影?

解决Mongoose嵌套数组筛选问题

假设你的movies集合中文档的cast数组结构类似这样:

{
  title: "壮志凌云",
  cast: [
    { actorId: "xxx123", name: "Tom Cruise" },
    { actorId: "yyy456", name: "其他演员" }
  ]
}

要筛选出包含指定Tom Cruise演员ID的电影,直接用Mongoose的点语法查询嵌套字段即可,不需要复杂的过滤函数:

// 替换成实际的Tom Cruise演员ID
const targetActorId = "xxx123";
const result = await Movie.find({
  "cast.actorId": targetActorId
});

补充说明

  • MongoDB会自动遍历cast数组中的每个元素,只要数组里有任意一个元素的actorId匹配目标值,就会返回该电影文档。
  • 如果需要只返回cast数组中匹配的那一项(而不是整个数组),可以加投影参数:
const result = await Movie.find(
  { "cast.actorId": targetActorId },
  { title: 1, "cast.$": 1 } // 只保留电影标题和匹配的演员项
);

内容的提问来源于stack exchange,提问作者AckermanShadow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:50:42