Java implementation of the operation of MongoDB connections, additions and deletions to check

Source: Internet
Author: User
Tags iterable mongoclient mongodb mongodb driver mongodb query package json tojson sonatype
Java implementation of the operation of MongoDB connections, additions and deletions to check

MongoDB jar Package Download
Java MongoDB Driver
Https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/
I downloaded it (mongo-java-driver-3.0.1.jar)

Java implementation MongoDB Connection close operation, write a mongodbhelper

Package Com.java.dao;

Import com.mongodb.MongoClient;

Import Com.mongodb.client.MongoDatabase;
        public class Mongohelper {static final String dbname = "Weibo"; 
        Static final String serveraddress = "127.0.0.1";

        static final int PORT = 27017; 
            Public Mongohelper () {} public mongoclient getmongoclient () {mongoclient mongoclient = null;  
                try {//Connect to MongoDB service mongoclient = new Mongoclient (serveraddress, PORT);
            System.out.println ("Connect to MongoDB successfully");
            catch (Exception e) {System.err.println (E.getclass (). GetName () + ":" + e.getmessage ());
        return mongoclient; Public mongodatabase getmongodatabase (mongoclient mongoclient) {mongodatabase mongodatabase = Nu
            ll
        try {if (mongoclient!= null) {//Connect to Database            Mongodatabase = Mongoclient.getdatabase (dbname);
                System.out.println ("Connect to DataBase successfully");  
                else {throw new RuntimeException ("Mongoclient cannot be empty");  
            } catch (Exception e) {e.printstacktrace ();
        return mongodatabase; } public void Closemongoclient (Mongodatabase mongodatabase,mongoclient mongoclient) {if (Mongod  
            Atabase!= null) {mongodatabase = null;  
            } if (mongoclient!= null) {mongoclient.close ();  

        } System.out.println ("Closemongoclient successfully");
 }  
}

After successful connection, check and modify Operation
This is the basic additions and deletions check the interface

Package Com.java.dao;


Import Java.util.Map;

Import org.bson.Document;
Import Com.mongodb.BasicDBObject;
Import com.mongodb.client.FindIterable;

Import Com.mongodb.client.MongoDatabase; /** * Dao Layer Interface * * */public interface Mongodao {/** * get Data by ID * * @param db * @param ta BLE * @param Id * @throws Exception/public map<string,integer> Querybyid (mongodatabase db, St

    Ring table, Object Id) throws Exception; /** * Insert Data * * @param db * @param table * @param document/public boolean Inse

    RT (Mongodatabase db, String table, Document doc); /** * Delete Many data.if doc is empty'll Delete all Data * @param db * @param table * @para

    M Document */public boolean Delete (Mongodatabase db, String table, Basicdbobject doc);
     /** * Update All Data * * @param db * @param table * @param olddoc * @param newdoc* * Public boolean update (Mongodatabase db, String table, Basicdbobject Olddoc, Basicdbobject newdoc);
 }

Implement the above interface and extend the method

Package Com.java.dao;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Map;

Import org.bson.Document;
Import com.java.exception.CustomException;
Import Com.java.service.JsonStrToMap;
Import Com.mongodb.BasicDBObject;
Import com.mongodb.client.FindIterable;
Import com.mongodb.client.MongoCollection;
Import Com.mongodb.client.MongoCursor;
Import Com.mongodb.client.MongoDatabase;
Import Com.mongodb.client.result.DeleteResult;

Import Com.mongodb.client.result.UpdateResult; /** * Implementation Interface * @author IIIP * * */public class Mongodaoimpl implements Mongodao {@Override public map<string ,integer> Querybyid (mongodatabase db, String table, Object Id) throws exception{Mongocollection<document&gt ;
        Collection = db.getcollection (table);
        Basicdbobject query = new Basicdbobject ("_id", id);
        DBObject interface and Basicdbobject object: Represents a specific record, Basicdbobject realized the DBObject, is the KEY-VALUE data structure, use and hashmap is basically consistent. Finditerable<document> iterable = CoLlection.find (query); for (Document dd:iterable) {//int dudu = Dd.getinteger ("Shanghai");//Read response data//System.out.print
ln ("Dudududu:" +dudu);
        } map<string,integer> jsonstrtomap = null;
        mongocursor<document> cursor = Iterable.iterator ();
            while (Cursor.hasnext ()) {Document user = Cursor.next ();
            String jsonstring = User.tojson (); Jsonstrtomap = Jsonstrtomap.jsonstrtomap (jsonstring);//Here I write my own method, mainly the package JSON string into the map format, prepare for the back, the method is placed in the back of the Sys

        TEM.OUT.PRINTLN ("Retrieve ID complete");
    return jsonstrtomap; /** * Based on a doc, retrieves all * @param db * @param table * @param doc/Public List when Doc is empty <Map<String,Integer>> Querybydoc (mongodatabase db, String table, Basicdbobject doc) {mongocollection
        <Document> collection = db.getcollection (table);
         finditerable<document> iterable = Collection.find (DOC); /** 
         * 1. Gets the iterator finditerable<document> * 2. Gets the cursor mongocursor<document> * 3. Traversal of retrieved document collection via cursor */list<map<string,integer>> List = new Arraylist<map<string,integ
        Er>> ();
        mongocursor<document> cursor = Iterable.iterator ();
            while (Cursor.hasnext ()) {Document user = Cursor.next ();
            String jsonstring = User.tojson ();
            map<string, integer> jsonstrtomap = Jsonstrtomap.jsonstrtomap (jsonstring);
        List.add (JSONSTRTOMAP);
        System.out.println ("Retrieve doc complete");
    return list; /** * Retrieves all and returns an iterator * @param db * @param table */Public List<map<string,integer>&gt ;
        Queryall (mongodatabase db, String table) {mongocollection<document> collection = db.getcollection (table);

        finditerable<document> iterable = Collection.find (); List<map<string,integer>> List = new arraylist<map<string,integer>> ();
        mongocursor<document> cursor = Iterable.iterator ();
            while (Cursor.hasnext ()) {Document user = Cursor.next ();
            String jsonstring = User.tojson ();
            map<string, integer> jsonstrtomap = Jsonstrtomap.jsonstrtomap (jsonstring);
        List.add (JSONSTRTOMAP);
        } System.out.println ("Retrieve all Completed");
    return list; /** * Convenient iterator finditerable<document>/public void printfinditerable (Finditerable<document&gt ;
        iterable) {mongocursor<document> cursor = Iterable.iterator ();
            while (Cursor.hasnext ()) {Document user = Cursor.next ();
        System.out.println (User.tojson ());
    } cursor.close (); @Override public boolean Insert (Mongodatabase db, String table, document document) {MONGOCOLLECTION&L
        T;document> collection = db.getcollection (table); CoLlection.insertone (document);
Long Count = Collection.count (document); System.out.println (Collection.getnamespace ());//weibo.area//System.out.println (Collection.getclass ());//cla SS Com.mongodb.MongoCollectionImpl//System.out.println (Collection.getdocumentclass ());//class org.bson.Document/ /System.out.println (Collection.getwriteconcern ());//writeconcern{w=1, wtimeout=0, Fsync=false, J=false//Syste
        M.out.println (Collection.getwriteconcern (). GETW ());//1 System.out.println ("Count:" +count);
            if (count = = 1) {System.out.println ("successful document Insertion");
        return true;
            }else{System.out.println ("document insert succeeded");
        return false; }/** * Insert many * @param db * @param table * @param document/Public Boolea n Insertmany (mongodatabase db, String table, list<document> documents) {mongocollection<document> C Ollection = db.getcollection (tABLE);
        Long Precount = Collection.count ();
        Collection.insertmany (documents);
        Long Nowcount = Collection.count ();
        System.out.println ("Inserted quantity:" + (Nowcount-precount));
            if ((nowcount-precount) = = Documents.size ()) {System.out.println ("document inserts multiple successes");
        return true;
            }else{System.out.println ("Document inserts multiple failures");
        return false; @Override public boolean Delete (Mongodatabase db, String table, Basicdbobject document) {MONGOC
        Ollection<document> collection = db.getcollection (table);
        Deleteresult Deletemanyresult = collection.deletemany (document);
        Long Deletedcount = Deletemanyresult.getdeletedcount ();
        System.out.println ("Deleted quantity:" +deletedcount);
            if (Deletedcount > 0) {System.out.println ("Document deletion multiple successes");
        return true;
            }else{System.out.println ("Document deletion multiple failures");
        return false;
 }
    }

    /**    * Delete A * @param db * @param table * @param document/public boolean deleteone (mongodatabase
        DB, String table, Basicdbobject document) {mongocollection<document> collection = db.getcollection (table);
        Deleteresult Deleteoneresult = collection.deleteone (document);
        Long Deletedcount = Deleteoneresult.getdeletedcount ();
        System.out.println ("Deleted quantity:" +deletedcount);
            if (Deletedcount = = 1) {System.out.println ("Document deletion a success");
        return true;
            }else{System.out.println ("Document deletion failed");
        return false; @Override public boolean update (Mongodatabase db, String table, Basicdbobject wheredoc,basicdbobject upd  
             Atedoc) {mongocollection<document> collection = db.getcollection (table); 
             Updateresult Updatemanyresult = Collection.updatemany (Wheredoc, New Document ("$set", Updatedoc)); Long Modifiedcount = Updatemanyresult. Getmodifiedcount ();

            System.out.println ("Modified quantity:" +modifiedcount);
                if (Modifiedcount > 0) {System.out.println ("Document updates multiple successes");
            return true;
                }else{System.out.println ("Document update failed");
            return false; }/** * Update one Data * @param db * @param table * @param wheredoc * @param updateD
            OC/Public boolean updateone (Mongodatabase db, String table, Basicdbobject wheredoc,basicdbobject updatedoc) {  
             Mongocollection<document> collection = db.getcollection (table); 
             Updateresult Updateoneresult = Collection.updateone (Wheredoc, New Document ("$set", Updatedoc));
             Long Modifiedcount = Updateoneresult.getmodifiedcount ();
             System.out.println ("Modified quantity:" +modifiedcount);
                 if (Modifiedcount = = 1) {System.out.println ("A successful document Update");
             return true; }else{System.out.println ("Document update failed");
             return false; }/** * Create collection * @param db * @param table */public void Createcol (Mongodatab
        ASE DB, String table) {db.createcollection (table);
    System.out.println ("Collection Creation succeeded");  /** * Drop a collection * @param db * @param table */public void Dropcol (Mongodatabase db,
        String table) {db.getcollection (table). Drop ();

    SYSTEM.OUT.PRINTLN ("set delete succeeded");
 }

}

One of the class methods used earlier Jsonstrtomap.jsonstrtomap

Package com.java.service;

Import Java.util.HashMap;
Import Java.util.Map;

Import Com.mongodb.util.JSON;

The public class Jsonstrtomap {

    /**
     * JSON string is converted to the map format
     * @param jsonstring
     * @return *

    * Public Static map<string, integer> Jsonstrtomap (String jsonstring) {
        Object parseobj = Json.parse (jsonstring); Deserialization converts JSON to object
        map<string, integer> map = (hashmap<string, integer>) parseobj;//Convert object to map
        return map;
    }


Test method

Package Com.java.dao;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;

Import org.bson.Document;
Import Com.mongodb.BasicDBObject;
Import com.mongodb.MongoClient;
Import com.mongodb.client.FindIterable;
Import Com.mongodb.client.MongoDatabase;


Import Com.mongodb.util.JSON; /** * Test class * @author Koo * * */public class Mainmonhelperimpl {public static void main (string[] args) {Mon
        Gohelper mongohelper = new Mongohelper ();
        Mongoclient mongoclient = Mongohelper.getmongoclient ();
        Mongodatabase mongodatabase = mongohelper.getmongodatabase (mongoclient);

Mongodaoimpl Mongodaoimpl = new Mongodaoimpl ();      * Directly using Basicdbobject for CRUD//Mongodaoimpl.insert (mongodatabase, table, new document (AREAMAP));//Insert Document// Mongodaoimpl.querybyid (Mongodatabase, table, 1)//retrieve event_id, note ID type is string or int//Basicdbobject Document2 = new Basi
Cdbobject ("likes", 1000); Document2.append ("event_id", "55"); Mongodaoimpl.querybydoc (mongodatabase, table, Document2)//Retrieve Doc, can be found according to Doc (Key,value), when Doc is empty, retrieve all//Mong Odaoimpl.queryall (mongodatabase, table);
Query All//Basicdbobject Document3 = new Basicdbobject ("likes", 200);  Mongodaoimpl.delete (mongodatabase, table, DOCUMENT3)//delete doc all information, when Doc is empty, delete all//Basicdbobject Document3 =
New Basicdbobject ("likes", 1000);    
Mongodaoimpl.deleteone (mongodatabase, table, DOCUMENT3)//delete doc//update document to change likes=100 document in document to likes=200
Basicdbobject Wheredoc = new Basicdbobject ("likes", 1000);
Basicdbobject Updatedoc = new Basicdbobject ("likes", 255); Mongodaoimpl.update (mongodatabase, table, Wheredoc, Updatedoc)/update all, find Olddoc data, update newdoc data//Basicdbobje
CT Wheredoc = new Basicdbobject ("likes", 255);
Basicdbobject Updatedoc = new Basicdbobject ("event_id", 205); Mongodaoimpl.updateone (mongodatabase, table, Wheredoc, Updatedoc)/update all, find Olddoc data, update Newdoc'sData//------------------------------------------------/** * Use map for CRUD Operations//System.
OUT.PRINTLN ("Test Map");
map<string, object> areaMap1 = new hashmap<string,object> ();
Areamap1.put ("_id", 2);
Areamap1.put ("Beijing", 5);
Areamap1.put ("Shanghai", 14);
Areamap1.put ("Guangzhou", 8);


         Areamap1.put ("Shenzhen", 0.5);  

        Deserialize map//SYSTEM.OUT.PRINTLN ("Map parse:" + json.parse (json.serialize (Areamap))); According to map to MongoDB query//finditerable<document> Querybydocresult = Mongodaoimpl.querybydoc (Mongodatabase, AREATABL
E, New Basicdbobject (AREAMAP1));


        Mongodaoimpl.printfinditerable (Querybydocresult);

Insert map to MongoDB//Mongodaoimpl.insert (Mongodatabase, areatable, New Document (AREAMAP1));
map<string, object> areaMap2 = new hashmap<string,object> ();
map<string, object> areaMap3 = new hashmap<string,object> (); Areamap2.put("_id", 10);
Areamap2.put ("Beijing", 5);
Areamap3.put ("_id", 11);
Areamap3.put ("Beijing", 5);
list<document> doclist = new arraylist<document> ();
Doclist.add (New Document (AREAMAP2));
Doclist.add (New Document (AREAMAP3));

        Mongodaoimpl.insertmany (Mongodatabase, areatable, doclist);
Delete MongoDB//Mongodaoimpl.delete (Mongodatabase, areatable, New Basicdbobject (AREAMAP1)) according to map;

        Mongodaoimpl.deleteone (Mongodatabase, areatable, New Basicdbobject (AREAMAP1));
Update MongoDB//map<string According to Map, object> updatedoc = new hashmap<string,object> ();
map<string, object> weheredoc = new hashmap<string,object> ();
Weheredoc.put ("_id", 4);
Updatedoc.put ("Shanghai", 25);
Mongodaoimpl.update (Mongodatabase, areatable, New Basicdbobject (Weheredoc), New Basicdbobject (UPDATEDOC)); Mongodaoimpl.updateone (Mongodatabase, areatable, New Basicdbobject (Weheredoc),New Basicdbobject (Updatedoc));
Search All//finditerable<document> Queryallresult = Mongodaoimpl.queryall (Mongodatabase, areaTable);
Mongodaoimpl.printfinditerable (Queryallresult);

    Mongohelper.closemongoclient (mongodatabase,mongoclient);
 }

}

Reference:
Mongoutil Java Heleper
http://blog.csdn.net/guoxingege/article/details/47439581

Grammar:
Http://www.runoob.com/mongodb/mongodb-java.html

Document
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/

Java MongoDB Driver
Https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.4.1/

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.