如何在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
相关产品推荐
相关产品推荐

