MongoDB University Third Week job--Deleting an array element in a document

Source: Internet
Author: User
Tags mongoclient mongo shell

The first two weeks of work is relatively simple, easy to fix, this week's work suddenly difficult to get up, the cost of a great effort to write, there are many needs to improve the place, at present can only be considered reluctantly realized the function.


Demand:

Homework:homework 3.1

Download the Students.json file from the Download handout link and import it to your local Mongo instance with this Comm And:

$ 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 would remove the lowesthomework score for each student. Since there is a single document for each student containing an array of scores, you'll 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 are a lot harder and that's the sort of the point. One-on-is-find the lowest homework in code and then update the scores array with the low homework pruned.

To confirm your is on the right track, here is some queries to run after your process the data with the correct answer sho Wn

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", "SCO Re ": 4.433956226109692},{" type ":" Quiz "," Score ": 65.50313785402548},{" type ":" Homework "," Score ": 89.5950384993947}] }

To verify the 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 would appear in the _id field of the resulting document.

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



The Java section code is as follows:



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 ()) {&NBsp;       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 =&nbSp Float.parsefloat (Homeworks.get (1));                               if   (Hw1stscore > hw2edscore) {                           hwmaxscore  = hw1stScore;               index = 3;             }else {              hwMaxScore =  hw2edscore;             index = 2;              }           &nBsp;               scores.remove ( Index);                           collection.update (New basicdbobject ("_id",  Cur.get ("_id")),              new  Basicdbobject ("$set",  new basicdbobject ("scores",  scores)));                         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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 ("=======");                                 }             }}


This article is from the "Big sword without front of the great Qiao Not Work" blog, please make sure to keep this source http://wuyelan.blog.51cto.com/6118147/1608008

MongoDB University Third Week job--Deleting an array element in a document

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.