javawithmongo.JavaWithMongo.java Source code

Java tutorial

Introduction

Here is the source code for javawithmongo.JavaWithMongo.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javawithmongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.text.ParseException;

import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

/**
 *
 * @author aaron
 */
public class JavaWithMongo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException, org.json.simple.parser.ParseException {

        // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
        // if it's a member of a replica set:
        MongoClient mongoClient = new MongoClient();

        JSONParser parser = new JSONParser();
        String ss = "[{\"school\":\"Unam Cch Plantel Sur\",\"schoolType\":\"High School\"},{\"school\":\"escuela secundaria diurna 281\",\"schoolType\":\"High School\",\"startYear\":2009},{\"school\":\"John F. Kennedy High School\",\"schoolType\":\"High School\"},{\"school\":\"UNAM FMVZ\",\"schoolType\":\"College\"},{\"school\":\"Facultad de Medicina Veterinaria y Zootecnia UNAM\",\"schoolType\":\"Graduate School\"}]";

        Object obj = parser.parse(ss);
        JSONArray array = (JSONArray) obj;
        System.out.println("The 2nd element of array");

        System.out.println(array.get(1));
        System.out.println();

        DB db = mongoClient.getDB("Gigya");
        DBCollection coll = db.getCollection("datos");

        BasicDBObject doc = new BasicDBObject("escuela", array);

        coll.save(doc);
        //        Set<String> colls = db.getCollectionNames();
        //
        //        for (String s : colls) {
        //            System.out.println(s);
        //        }
        //        
        //        
        //        DBObject myDoc = coll.findOne();
        //        System.out.println(myDoc.get("nombre"));

    }

}