如何基于嵌套元素多属性实现MongoDB数据过滤查询
MongoDB嵌套多属性过滤查询方案
查询逻辑说明
- 要匹配嵌套数组中同一个元素同时满足两个属性条件,必须使用*$elemMatch*操作符,不可直接写多个键值对匹配,否则会出现跨元素匹配的错误
- 如果需要仅返回匹配到的符合条件的
items子项,可搭配聚合的$filter操作符实现精准过滤
基础查询(返回包含符合条件items的全部父文档)
db.collection.find({ "item.items": { $elemMatch: { "elems": { $elemMatch: { id: 111, isActive: true } } } } })
精准过滤查询(仅返回items数组中符合要求的条目)
db.collection.aggregate([ // 先过滤出包含符合条件items的父文档,减少后续计算量 { $match: { "item.items.elems": { $elemMatch: { id: 111, isActive: true } } } }, // 过滤items数组,只保留elems符合要求的子项 { $addFields: { "item.items": { $filter: { input: "$item.items", as: "item", cond: { $anyElementTrue: { $map: { input: "$$item.elems", as: "elem", in: { $and: [ { $eq: ["$$elem.id", 111] }, { $eq: ["$$elem.isActive", true] } ] } } } } } } } }, // 可选:过滤掉items为空的文档 { $match: { "item.items": { $ne: [] } } } ])
结果说明
针对你提供的示例数据执行上述查询,只会返回items.id为1的条目,items.id为2的条目因为elems中id=111对应的isActive为false,会被直接排除。
内容的提问来源于stack exchange,提问作者snoksdom
相关产品推荐
相关产品推荐

