The solution Homework 3.1 M101JS: MongoDB for Node.js Developers

Write a program in the language of your choice that will remove the lowest homework score for each student. Since there is a single document for each student containing an array of scores, you will need to update the scores array and remove the homework.

Remember, just remove a homework score. Don’t remove a quiz or an exam!

Hint/spoiler: With the new schema, this problem is a lot harder and that is sort of the point. One way is to find the lowest homework in code and then update the scores array with the low homework pruned.

To confirm you are on the right track, here are some queries to run after you process the data with the correct answer shown:

Let us count the number of students we have:

  1. use school
  2. DB.students.count()

The answer will be 200.

Let’s see what Tamika Schildgen’s record looks like:

  1. db.students.find( { _id : 137 } ).pretty( )

This should be the output:

{
	"_id" : 137,
	"name" : "Tamika Schildgen",
	"scores" : [
		{
			"type" : "exam",
			"score" : 4.433956226109692
		},
		{
			"type" : "quiz",
			"score" : 65.50313785402548
		},
		{
			"type" : "homework",
			"score" : 89.5950384993947
		}
	]
}

To verify that you have completed this task correctly, provide the identity (in the form of their _id) of the student with the highest average in the class with following query that uses the aggregation framework. The answer will appear in the _id field of the resulting document.

db.students.aggregate( { ‘$unwind’ : ‘$scores’ } , { ‘$group’ : { ‘_id’ : ‘$_id’ , ‘average’ : { $avg : ‘$scores.score’ } } } , { ‘$sort’ : { ‘average’ : -1 } } , { ‘$limit’ : 1 } )

Solution:

13

Enter 13 and submit.

Create a file app.js and insert the following code:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/school', function(err, db){
  if(err) throw err;
  var query = {};

  db.collection('students').find(query).toArray(function(err, docs) {
    if(err) throw err;

    var min;
    var doc;
    var value;
    for (var i = 0; i < docs.length; i++){
        doc = docs[i];
        min = -1;
        for(var j = 0; j < doc.scores.length; j++){
           value = doc.scores[j];
           if(value.type === "homework"){
             if(min === -1 || value.score < doc.scores[min].score ){
               min = j;
             }
           }
        }
        console.log("Ant length :" + doc.scores.length + " min : " + min);
        // important: Array.splice need the number of elements to delete...  splice(index, )
        doc.scores.splice(min, 1);
        console.log("Pos length :" + doc.scores.length);
        db.collection('students').save(doc, function(err, saved) {
          if(err) throw err;
          console.log("Doc saved: " + saved);

        });
    }
    //console.dir("Result" + docs);
    console.dir("End");
    return db.close();
  });

});

Now run it with node app.js

Check your result with the following query:

db.students.find( { _id : 13 } ).pretty( )

Result:

{
        "_id" : 13,
        "name" : "Jessika Dagenais",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 90.47179954427436
                },
                {
                        "type" : "quiz",
                        "score" : 90.3001402468489
                },
                {
                        "type" : "homework",
                        "score" : 95.17753772405909
                }
        ]
}

You can see the lowest homework scores are removed from all documents.

Now again run

db.students.aggregate( { '$unwind' : '$scores' } , { '$group' : { '_id' : '$_id' , 'average' : { $avg : '$scores.score' } } } , { '$sort' : { 'average' : -1 }, { '$limit' : 1 } )

The result will be:

{ "_id" : 13, "average" : 91.98315917172745 }

I have submitted “13” and the answer is correct but if you have any great solution then please let me know as well as if any problem then let me know so that we can solve together.

Previous articleFinal: Question 1 M101JS: MongoDB for Node.js Developers
Next article%type: !message in %function (line %line of %file) Drupal error
Author of three Opencart book. The recent Opencart 4 book is at https://amzn.to/4dOlbOR

LEAVE A REPLY

Please enter your comment!
Please enter your name here