com.tengen.Week3Hw3_1.java Source code

Java tutorial

Introduction

Here is the source code for com.tengen.Week3Hw3_1.java

Source

/*
 * Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.tengen;

import com.mongodb.*;

import java.net.UnknownHostException;

public class Week3Hw3_1 {
    public static void main(String[] args) throws UnknownHostException {
        MongoClient client = new MongoClient();

        DB database = client.getDB("school");
        DBCollection collection = database.getCollection("students");

        DBCursor cursor = collection.find();
        int student_id = -1;
        int count = 0;

        try {
            while (cursor.hasNext()) {
                DBObject student = cursor.next();
                //student.grades;
                BasicDBObject searchQuery = new BasicDBObject().append("_id", student.get("_id"));
                BasicDBList scores = (BasicDBList) student.get("scores");
                BasicDBObject[] scoresArr = scores.toArray(new BasicDBObject[0]);
                double score = 100.0;
                BasicDBObject rem = new BasicDBObject();
                for (BasicDBObject dbObj : scoresArr) {
                    String type = dbObj.get("type").toString();
                    if (type.equals("homework")) {
                        double s = Double.parseDouble(dbObj.get("score").toString());

                        if (score > s) {
                            score = s;
                            rem = dbObj;
                        }
                    }
                }
                BasicDBObject update = new BasicDBObject("scores", rem);
                collection.update(searchQuery, new BasicDBObject("$pull", update));
            }
        } finally {
            cursor.close();
        }
    }
}