MongoDB聚合中$match的$in查询失效问题求助
问题解决方法
错误原因分析
你的代码存在两个关键问题,导致返回空数组:
- 字段名大小写不匹配:
bookSchema里定义的关联字段是小写的author,但查询时写的是大写的'Author',MongoDB对字段名大小写敏感,因此无法匹配到数据。 - $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
相关产品推荐
相关产品推荐

