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

MongoDB聚合中$match的$in查询失效问题求助

问题解决方法

错误原因分析

你的代码存在两个关键问题,导致返回空数组:

  1. 字段名大小写不匹配:bookSchema里定义的关联字段是小写的author,但查询时写的是大写的'Author',MongoDB对字段名大小写敏感,因此无法匹配到数据。
  2. $in参数类型错误:你直接传入了完整的作者对象数组,但书籍集合中author字段存储的是作者的ObjectId,不是完整对象,所以无法匹配。

正确实现方式

首先从作者对象数组中提取出所有_id组成新数组:

const authorIds = authors.map(author => author._id);

方法一:使用普通find查询(更简洁高效)

const filteredBooks = await Book.find({ author: { $in: authorIds } });

方法二:使用aggregate查询(修正后)

const filteredBooks = await Book.aggregate([
  { $match: { author: { $in: authorIds } } }
]);

补充说明

如果需要同时返回关联的作者信息,可以结合populate方法:

const filteredBooks = await Book.find({ author: { $in: authorIds } }).populate('author');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:45:30