mongodb - 查询以在对象数组中的所有对象都匹配时返回结果
问题描述
我的文档结构如下所示:
users : [
{_id:1,
'name': 'xxxxx',
'children':[
{age:13, weight: 80 lbs},
{age: 12, weight: 65 lbs}
]
}
{_id:2,
'name': 'yyyyy',
'children':[
{age:11, weight: 65 lbs},
{age: 9, weight: 55 lbs}
]
}
]
我正在尝试获取子数组中所有元素都小于 12 岁的对象。所以预期的输出看起来像:
[
{_id:2,
'name': 'yyyyy',
'children':[
{age:11, weight: 65 lbs},
{age: 9, weight: 55 lbs}
]
}
]
我尝试了 elem match 但它只查找数组中的任何匹配项。我正在寻找所有的比赛。我试过这个,但没有用。
{"children":{"$all":[{"$elemMatch":{"age":{"$lte":12}}}]}}
解决方案
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [ { $reduce: { input: "$children",
initialValue: true,
in: { $cond: [ { $gte: [ "$$this.age", 12 ] }, "$$value", false ] }
} },
true
]
}
}
}
])
聚合使用$reduce数组运算符检查children
数组中的所有元素是否age
大于或等于 12。归约操作返回布尔值true
或false
(仅当所有数组元素都匹配时才为真)。$match
阶段过滤带有结果的文档true
。
推荐阅读
- javascript - JS:通过使用 settimout 调用自身来等待函数 - 如何处理参数?
- python - Jupyter如何在后台运行单元格?
- cocoapods - Podspec 错误:`source_files` 模式与任何文件都不匹配
- sails.js - Sails 中的 Create 方法创建新记录但返回错误请求
- php - 覆盖作曲家依赖自动加载指令
- angularjs - 我们可以使用 TestCafe 自动化 Angular 或 reactjs 应用程序吗?
- python - 如果 json 文件中的 KeyAttribute 不可用,如何传递空值(在 python 中获取 Key Error)
- ios - 单元格尺寸 rowHeight 大小
- spss-modeler - 更改神经网络节点 SPSS Modeler 中的学习率
- groovy - Groovy 是否有专门的语法来查找集合中的元素,或者如果找不到则抛出异常?