如何使用Mongoose查询对象数组并仅返回符合过滤条件的匹配对象
Mongoose 查询实现方案
要实现过滤嵌套数组rounds.matches中所有满足条件的子项,需要使用Mongoose聚合管道,普通find方法无法直接过滤返回数组内的所有匹配子元素,具体实现代码如下:
// 请将下方的Game替换为你实际使用的Mongoose模型名 const result = await Game.aggregate([ // 第一阶段:先筛选出至少包含1条匹配记录的文档,缩小后续处理范围 { $match: { $or: [ { "rounds.matches.firstParticipant.address": "789" }, { "rounds.matches.secondParticipant.address": "789" } ] } }, // 第二阶段:拆分嵌套的matches数组,将每个子项拆分为独立文档 { $unwind: "$rounds.matches" }, // 第三阶段:过滤出满足地址条件的单条match记录 { $match: { $or: [ { "rounds.matches.firstParticipant.address": "789" }, { "rounds.matches.secondParticipant.address": "789" } ] } }, // 第四阶段:调整返回结构,直接返回match对象作为结果 { $replaceRoot: { newRoot: "$rounds.matches" } } ])
执行上述代码后得到的result就是你预期的返回结果。如果你的查询目标是指定_id为25113的单条文档,可以在第一阶段的$match中补充_id: "25113"条件进一步缩小范围。
内容的提问来源于stack exchange,提问作者Daywison Ferreira Leal
相关产品推荐
相关产品推荐

