首页 > 解决方案 > 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 }}})

标签: mongodb

解决方案


我认为这是你需要的:

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/


推荐阅读