Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - optimize query- aggregration framework mongodb

A student can give any no of tests. I need to get the marks of last 5 tests(or dataLimit ) given by each student in a class in given time.

Limit can not be used before grouping as any student can give the test any no of times.

The group operation is giving memory restriction error. "Exceeded memory limit for $group, but didn't allow external sort" Currently i have allowed the disk space usage as workaround, but how can i optimize this query ?

    {
        "_id" : ObjectId("5fa98dfedc0e820001326944"),
        "school" : "ABC",
        "scholbranch" : "XYZ",
        "class" : "7",
        "section" : "C",
        "studentname" : "Student 1",
        "testmarks" : "90",
        "dateTime" : ISODate("2020-11-09T18:44:14.000Z")
    }
    
        Query query = new Query();
        List<Criteria> docCriterias = new ArrayList<Criteria>();
        docCriterias.add(Criteria.where("school").is(school));
        docCriterias.add(Criteria.where("scholbranch").is(scholbranch));
        docCriterias.add(Criteria.where("class").is(class));
        docCriterias.add(Criteria.where("section").is(section));
        docCriterias.add(Criteria.where("dateTime").gte(date1));
        docCriterias.add(Criteria.where("dateTime").lt(date2));
        Criteria criteria = new Criteria();
        criteria.andOperator(docCriterias.toArray(new Criteria[docCriterias.size()]));
        int datalimit = noOfData;
        
        MatchOperation matchStage = Aggregation.match(criteria);

        SortOperation sortByDateDesc = Aggregation.sort(new Sort(Direction.DESC, "dateTime"));

        GroupOperation groupBy = Aggregation.group("$studentname").push(new BasicDBObject("studentname", "$studentname")
                .append("testmarks", "$testmarks").append("dateTime", "$dateTime")).as("val");

        ProjectionOperation projectToMatchModel = Aggregation.project().and("$_id").as("student").and("val")
                .slice(datalimit).as("mostRecentVal");

        Aggregation aggregation = Aggregation.newAggregation(matchStage, sortByDateDesc, groupBy,
                projectToMatchModel);
question from:https://stackoverflow.com/questions/65885744/optimize-query-aggregration-framework-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...