如何从MongoDB嵌套文档中筛选获取目标数据?
MongoDB数组过滤查询问题
原始文档结构
[ { _id: ObjectId("6386ef039775398be3620c76"), firstName: 'A', lastName: 'BA', age: 34, history: [ { disease: 'fever', cured: true }, { disease: 'malaria', cured: false } ] }, { _id: ObjectId("6386ef239775398be3620c77"), firstName: 'AA', lastName: 'BA', age: 24, history: [ { disease: 'cold', cured: true }, { disease: 'thyroid', cured: false } ] } ]
预期查询结果
[ { _id: ObjectId("6386ef039775398be3620c76"), firstName: 'A', lastName: 'BA', age: 34, history: [ { disease: 'malaria', cured: false } ] }, { _id: ObjectId("6386ef239775398be3620c77"), firstName: 'AA', lastName: 'BA', age: 24, history: [ { disease: 'thyroid', cured: false } ] } ]
尝试过的错误查询
db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
db.collection.aggregate([ { $project: { history: { $filter: { input: "$history", as: "items", cond: { cured: false } }, }, }, ]);
db.collection.find({history:{$elemMatch:{cured:true}}},{'history.cured':1})
疑问与解答
1. 是否可以直接通过查询得到预期结果?
可以。使用聚合管道的$filter操作符就能精准过滤数组中符合条件的元素,同时保留文档的其他字段;在MongoDB 4.4及以上版本,也可以在find方法的投影阶段直接使用$filter实现相同效果。
2. 尝试的查询问题出在哪里?
- 第一个查询:
find方法的查询条件参数不能使用$filter($filter是聚合操作符,仅适用于聚合管道或投影阶段),且语法不完整,缺少闭合括号,无法执行。 - 第二个聚合查询:
$filter的cond条件写法错误,没有正确引用数组元素的字段。需要使用变量$$items来指代当前遍历的数组元素,正确条件应为{$eq: ["$$items.cured", false]},直接写{ cured: false }MongoDB无法识别这是对数组元素的判断。 - 第三个
find查询:查询条件是筛选history中存在cured: true的文档,与需求(保留未治愈的记录)完全相反;同时投影仅指定history.cured:1,只会返回整个history数组里的cured字段,不会过滤数组元素。
3. 应该学习哪些资料来掌握这类高级查询概念?
- 重点学习MongoDB官方文档中的聚合管道操作符章节,尤其是数组操作符(
$filter、$map、$reduce等)的用法 - 熟悉官方文档的查询投影章节,了解如何在
find中使用投影操作符处理嵌套数据 - 跟着官方的聚合管道教程练习,掌握多阶段组合处理复杂数据的逻辑
- 多做数组过滤、嵌套文档查询的实例练习,加深对操作符的理解和运用
内容的提问来源于stack exchange,提问作者HASH SHA-256
相关产品推荐
相关产品推荐

