MongoDB University 第三周作業——刪除文檔中的數組元素

來源:互聯網
上載者:User

標籤:mongo db java 數組

前兩周的作業比較簡單,輕鬆搞定,這周的作業突然難起來了,費了好大勁兒寫完,還有很多需要改進的地方,目前只能算是勉強實現了功能。


需求: 

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<String> homeworks= new ArrayList<String>();        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<BasicDBObject> scores=(ArrayList<BasicDBObject>)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("=======");                               }            }}


本文出自 “重劍無鋒 大巧不工” 部落格,請務必保留此出處http://wuyelan.blog.51cto.com/6118147/1608008

MongoDB University 第三周作業——刪除文檔中的數組元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.