Tutorial MongoDB Tutorial

Discussion in 'Resources' started by Funergy, Nov 22, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Funergy

    Hello there,
    First of all I'm quite new to NON-SQL databases
    but this tutorial is probably good explained.
    And I've added some debugging messages
    Code:
    import java.util.ArrayList;
     
    import org.bukkit.Bukkit;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
     
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.MongoClient;
    import com.mongodb.util.JSON;
     
    /**
    * @author Funergy
    *
    */
    public class Driver {
        private MongoClient mc;
        private DB db;
     
        /*
        * Create a connection to the server
        * and select the database
        */
        public Driver(){
            Bukkit.broadcastMessage("Starting!");
     
            try {// new MongoClient(<server ip without port>,<the port>);
                mc = new MongoClient("randomserverip",randomport);
                Bukkit.broadcastMessage("Connected!");
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            db = mc.getDB("funergydev");
        }
     
        /*
        * Login with the user associated with the database
        */
        @SuppressWarnings("deprecation")
        public void auth(String user, String pass){
            db.authenticate(user,pass.toCharArray());
            Bukkit.broadcastMessage("Authenticated!");
     
        }
        /*
        * Close the Connection
        */
        public void close(){
            mc.close();
            Bukkit.broadcastMessage("Closed!");
     
        }
        /*
        * Insert a document into the collection of documents
        */
        public void insert(String uuid){
            /*
            * We select the collection of documents in the database
            */
            DBCollection coll = db.getCollection("test");
     
            /*
            * This is how to create a list. this can be handy with
            * creating a Friend system/Party system
            */
            ArrayList<String> l = new ArrayList<String>();
            l.add("Funergy");
            l.add("DubstepPrins");
            /*
            * We create an Object and this will be an object specially for MongoDB
            * and we append all the other data
            *
            * new BasicDBObject(<the name/key>,<the value>)
            * this will look like this in a JSON string
            * {UUID: <your value>}
            *
            * We will do the same for all the other settings
            */
            BasicDBObject doc = new BasicDBObject("UUID", uuid)
            .append("rank", "Owner")
            .append("coins", 10)
            .append("friends", l);
            /*
            * Here we will insert the document into the collection of documents called test
            */
            coll.insert(doc);
                Bukkit.broadcastMessage("Inserted!");
     
        }
        /*
        * Here we get a document of the player with the UUID: 4
        * We create a DBCursor to query a document
        * then we use find method to find the object we defined in a BasicDBObject
        */
        @SuppressWarnings("static-access")
        public void get(){
            DBCollection coll = db.getCollection("test");
            BasicDBObject query = new BasicDBObject("UUID", "4");
            DBCursor cursor = coll.find(query);
     
            /*
            * The same as in MySQL we check if it has found anything
            * We convert the result to a JSON string in place of a BSON string
            *
            */
            if(cursor.hasNext()){
            JSON json = new JSON();
            String s = json.serialize(cursor.next());
            System.out.println(s);
                try {
                    /*
                    * We call the parse method to actually analyse the JSON string to java objects
                    */
                    parse(s);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                System.out.println("MongoDB did not find this DBObject!");
            }
            cursor.close();
        }
        /*
        * Here we update a document in the collection of document called "test"
        */
        public void update(){
            DBCollection coll = db.getCollection("test");
            /*
            * we use the getAll() method to get the document of the player before the update
            * this is just for testing
            */
            BasicDBObject obj = getAll();
            /*
            * Here we create an object to edit. so we get the document
            * but now we remove the variable coins and insert it again with the value you want
            */
            BasicDBObject editobj = getAll();
            editobj.remove("coins");
            editobj.put("coins", 9999);
            /*
            * Here we actually do the update to the collection of documents
            * coll.update(the document before, the document to replace with the document before);
            */
            coll.update(obj, editobj);
     
        }
        /*
        * Here we get the document of the player with the UUID: 4
        * this is the same as the get method but with some little changes
        * PLEASE DON'T SKIP THIS
        */
        public BasicDBObject getAll(){
            DBCollection coll = db.getCollection("test");
            BasicDBObject query = new BasicDBObject("UUID", "4");
            DBCursor cursor = coll.find(query);
     
            if(cursor.hasNext()){
                /*
                * I place of parsing the BSON string to a JSON string
                * we just return the BasicDBObject/DocumentData
                */
            return(BasicDBObject) cursor.next();
         
            }else{
                System.out.println("MongoDB did not find this DBObject!");
            }
            return null;
        }
        /*
        * Here we parse the JSON String to normal variables
        */
        public void parse(String js) throws ParseException{
            /*
            * Here we initiate the JSON Parser
            */
            JSONParser parser = new JSONParser();
            /*
            * Here we create a JSONObject this is the same as a BasicDBObject
            * We parse the JSON String to JSON objects
            * so a JSON Object cuts the JSON string in to little parts of Keys and Values like a HashMap
            * so if we have
            * {name: "swag"}
            * and we parse it we should get the object.
            * with calling the object
            * and getting the value of the key called name.
            * We get returned a string with "swag" in it.
            *
            * More info down here
            */
            JSONObject object = (JSONObject) parser.parse(js);
            /*
            * Here we get a part of the JSONObject this acts like a HashMap
            * You have Keys and Values
            */
            System.out.println(object.get("UUID"));
            System.out.println(object.get("rank"));
            System.out.println(object.get("coins"));
            /*
            * Here we want to get the friends the player has
            * this is an array of strings so this not the same as just 1 string
            * so we convert the friends part of the JSONObject to a JSONArray
            */
            JSONArray array =(JSONArray) object.get("friends");
            /*
            * Here we loop through the JSONArray
            * and you can put them into an ArrayList or any other list
            *
            * But in this case we print it in the console
            */
            for(Object friends : array){
                System.out.println(friends);
            }
     
     
     
        }
     
     
     
    }
    If you have any questions message me then!

    Regards Funergy
     
    ChipDev, indyetoile and Regablith like this.
  2. Offline

    Jam2400

    Thanks for this! Could you put this into a gist on GitHub?
     
Thread Status:
Not open for further replies.

Share This Page