前两周的作业比较简单,轻松搞定,这周的作业突然难起来了,费了好大劲儿写完,还有很多需要改进的地方,目前只能算是勉强实现了功能。


需求: 

HOMEWORK: HOMEWORK 3.1


Download the students.json file from the Download Handout link and import it into your local Mongo instance with this command:

$ mongoimport -d school -c students < students.json

This dataset holds the same type of data as last week's grade collection, but it's modeled differently. You might want to start by inspecting it in the Mongo shell.

Write a program in the language of your choice that will remove the lowesthomework 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:

> use school
> db.students.count() 
200

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

> db.students.find( { _id : 137 } ).pretty( )
{
	"_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 } )



Java 部分代码如下:


import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class Week3Homework1 {
    public static void main(String[] args) throws UnknownHostException {
        MongoClient client = new MongoClient();
        DB database = client.getDB("school");
        DBCollection collection = database.getCollection("students");
  
        
        DBObject query = new BasicDBObject("scores.type","homework");
        DBCursor cursor = collection.find(query)
        .sort(new BasicDBObject("_id",1));
        
        ArrayList homeworks= new ArrayList();
        float hw1stScore = 0;
        float hw2edScore = 0;
        float hwMaxScore = 0;
        int index = 0;
        BasicDBObject newScroes = new BasicDBObject();
        
        while(cursor.hasNext()){
        BasicDBObject cur = (BasicDBObject)cursor.next();
        
     
        @SuppressWarnings("unchecked")
ArrayList scores=(ArrayList)cur.get("scores");  
        
        if(!homeworks.isEmpty()){
        homeworks.clear();
        }
        
        
            for(BasicDBObject types:scores){              
            String type_name  = types.getString("type");            
                  
                if(type_name.equals("homework")){
                  homeworks.add(types.getString("score"));
                }      
            }
            
             hw1stScore = Float.parseFloat(homeworks.get(0));
             hw2edScore = Float.parseFloat(homeworks.get(1));    
             
             if (hw1stScore > hw2edScore){             
             hwMaxScore = hw1stScore;  
            index = 3;
             }else {
             hwMaxScore = hw2edScore;
             index = 2;
             }
             
             scores.remove(index);
             
             collection.update(new BasicDBObject("_id", cur.get("_id")), 
             new BasicDBObject("$set", new BasicDBObject("scores", scores)));
                 
            System.out.println(cur);
                          
 //           System.out.println("Student_name: " + cur.getString("name"));
  //          System.out.println("Student_id: " + cur.getString("_id"));
  //          System.out.println("Homework First Score:"+ hw1stScore);
  //          System.out.println("Homework Second Score:"+ hw2edScore);
   //         System.out.println("Highest Homework Score: " + hwMaxScore);
              System.out.println("=======");               
        
        }
        
    }
}