如何编写Mongoose查询以仅返回嵌套数组中匹配的article对象ID
你原来的查询语句只能返回完整父文档,普通投影无法过滤嵌套数组内的非匹配元素,使用聚合管道就可以实现仅返回匹配的文章ID,代码示例如下:
const targetName = "Why to study data3?" // 替换为你的搜索关键词 const result = await MyModal.aggregate([ // 过滤包含目标文章的父文档,缩小查询范围 { $match: { "content.articles.article_name": { $regex: targetName, $options: "i" } } }, // 展开外层数组,你的模型中如果是Data数组就替换为$Data { $unwind: "$content" }, // 展开内层文章数组 { $unwind: "$content.articles" }, // 二次匹配精准定位目标文章 { $match: { "content.articles.article_name": { $regex: targetName, $options: "i" } } }, // 仅返回需要的文章ID字段 { $project: { _id: 0, articleId: "$content.articles._id" } } ]) // 单匹配场景直接取第一条结果即可 const matchedId = result[0]?.articleId
如果搜索关键词可能匹配多篇文章,上述代码会返回所有匹配的文章ID列表,你可以按需取用。如果你的模型中存储的外层数组字段是Data而非示例中的content,把代码中所有的content替换为Data即可正常运行。
内容的提问来源于stack exchange,提问作者gaurav parkash
相关产品推荐
相关产品推荐

