mongodb - MongoDB:从嵌套数组中过滤掉元素
问题描述
我有一个类似于以下的数据收集:
{
"_id" : 1,
"name" : "Class 1",
"students" : [
{ "rollNo" : 10001, "name" : "Ram", "score" : 65 },
{ "rollNo" : 10002, "name" : "Shyam", "score" : 90 },
{ "rollNo" : 10003, "name" : "Mohan", "score" : 75 }
]
},
{
"_id" : 2,
"name" : "Class 2",
"students" : [
{ "rollNo" : 20001, "name" : "Krishna", "score" : 88 },
{ "rollNo" : 20002, "name" : "Sohan", "score" : 91 },
{ "rollNo" : 20003, "name" : "Radhika", "score" : 82 },
{ "rollNo" : 20004, "name" : "Komal", "score" : 55 }
]
},
{
"_id" : 3,
"name" : "Class 3",
"students" : [
{ "rollNo" : 30001, "name" : "Monika", "score" : 77 },
{ "rollNo" : 30002, "name" : "Rahul", "score" : 81 }
]
}
在这种情况下,我想抓取所有分数大于或等于 90 的学生。预期输出为:
{
"_id" : 1,
"name" : "Class 1",
"students" : [
{ "rollNo" : 10002, "name" : "Shyam", "score" : 90 }
]
},
{
"_id" : 2,
"name" : "Class 2",
"students" : [
{ "rollNo" : 20002, "name" : "Sohan", "score" : 91 },
]
},
我尝试了以下方法,但它抓住了所有 1 类和 2 类
db.school.find({ $match : {'students.score': { $gte : 90 }}})
解决方案
我认为这是你需要的:
db.school.aggregate([
{
$project: {
students: {
$filter: {
input: "$students",
as: "student",
cond: { $gte: ["$$student.score", 90] }
}
},
name: 1,
_id: 1
}
},
{ $match: { students: { $exists: 1, $ne: [] } } }
])
但这对我来说似乎不够优雅。必须有更好的解决方案。
你可以在这里阅读: https ://docs.mongodb.com/manual/reference/operator/aggregation/filter/
推荐阅读
- javascript - 如何从随机选择中排除数组元素
- r - 如何将数据帧随机拆分为行,但每个集群在 R 中的值的累积和完全相同
- java - 从 Applications/app.app 运行 jar 的 MacOS 在加载 .fxml 期间以不正确的路径错误结束
- python - 如何使用 SimpleImputer 类在具有不同常量值的不同列中估算缺失值?
- javascript - 从对象列表中选择唯一的子对象并使用 Ramda 转换它们
- python - 为什么 np.pad 没有按我期望的方式工作?
- ios - 在另一个视图控制器中更改对象的属性
- ios - 在核心文本动画中存在位置问题
- reactjs - 如何在不干扰主项目的情况下将故事书作为 git 子模块运行?
- r - 如何使用 ggplot 制作小提琴图,没有任何变量列?