MongoDB Tool class and test class "Java"

Source: Internet
Author: User
Tags mongoclient name database

Tag: info IV return query gets ESS limit Apache TCL

Java Operations MONGO Tool class
Package Utils;import Com.mongodb.mongoclient;import Com.mongodb.mongocredential;import com.mongodb.ServerAddress; Import Com.mongodb.client.finditerable;import Com.mongodb.client.mongocollection;import Com.mongodb.client.mongocursor;import Com.mongodb.client.mongodatabase;import com.mongodb.client.model.Filters; Import Com.mongodb.client.result.updateresult;import Org.apache.commons.lang3.stringutils;import Org.apache.log4j.logger;import Org.bson.document;import Java.util.arraylist;import Java.util.Arrays;import    Java.util.list;import Java.util.map;public class Mongodbutil {private static mongodbutil mongodbutil;    private static final String please_send_ip = "No incoming IP or port number";    private static final String please_instance_mongoclient = "please instantiate mongoclient";    private static final String please_send_mongo_repository = "Please specify the MONGO library to be deleted";    private static final String delete_mongo_repository_exception = "Delete MONGO library exception"; private static final String delete_mongo_repository_success = "Bulk Delete MONGOLibrary Success ";    private static final String not_delete_mongo_repository = "MONGO library not deleted";    private static final String delete_mongo_repository = "successfully deleted MONGO Library:";    private static final String Create_mongo_collection_note = "Please specify the library to be created";    private static final String No_this_mongo_database = "The specified MONGO library was not found";    private static final String create_mongo_collection_success = "Create MONGO library succeeded";    private static final String create_mongo_collection_exception = "Create MONGO library error";    private static final String not_create_mongo_collection = "MONGO library COLLECTION not created";    private static final String Create_mongo_collection_such = "Create MONGO library COLLECTION:";    private static final String no_found_mongo_collection = "MONGO library COLLECTION not found";    private static final String insert_documen_exception = "Insert document Failed";    private static final String insert_documen_successs = "Insert Document succeeded";    private static final Logger Logger = Logger.getlogger (Mongodbutil.class); Private Mongodbutil () {} private static class singleholder{PrivAte static Mongodbutil Mongodbutil = new Mongodbutil ();    } public static Mongodbutil instance () {return singleholder.mongodbutil; } public static Mongodbutil getmongodbutilinstance () {if (Mongodbutil = = null) {return new Mongodbutil        ();    } return mongodbutil; /** * Get MongoDB Connection * @param host * @param port * @return */public mongoclient Getmongoconnect (            String Host,integer Port) {if (Stringutils.isblank (host) | | null = = port) {logger.error (PLEASE_SEND_IP);        return null;    } return new Mongoclient (host, Port); }/** * Bulk delete MONGO library * @param mongoclient * @param dbnames * @return */public String Bulkdropdata        Base (mongoclient mongoclient,string...dbnames) {if (null = = Mongoclient) return please_instance_mongoclient;        if (Null==dbnames | | dbnames.length==0) {return please_send_mongo_repository; } try {ArRays.aslist (dbnames). ForEach (DbName-Mongoclient.dropdatabase (dbName));        Logger.info (delete_mongo_repository_success);            }catch (Exception e) {e.printstacktrace ();        Logger.error (delete_mongo_repository_exception); } return dbnames = = null?    Not_delete_mongo_repository:delete_mongo_repository + string.join (",", dbnames);      /** * Create Collection * @param mongoclient * @param dbName * @param collections * For the specified database @return */Public String createcollections (mongoclient mongoclient,string dbname,string...collections) {if (null = =        mongoclient) return please_instance_mongoclient;        if (null==collections | | collections.length==0) {return create_mongo_collection_note;        } mongodatabase mongodatabase = Mongoclient.getdatabase (dbName);        if (null = = Mongodatabase) return no_this_mongo_database; try {Arrays.aslist (collections). ForEach (Collection-MONGODatabase.createcollection (collection));            Logger.info (create_mongo_collection_success); return collections = = null?        Not_create_mongo_collection:create_mongo_collection_such + string.join (",", collections);            }catch (Exception e) {e.printstacktrace ();        Logger.error (create_mongo_collection_exception);    } return null;     }/** * Get mongocollection * @param mongoclient * @param dbName * @param collection * @return * *        Public mongocollection<document> getmongocollection (mongoclient mongoclient,string dbName,String collection) {        if (null = = mongoclient) return null;        if (Stringutils.isblank (dbName)) return null;        if (Stringutils.isblank (collection)) return null;        Mongodatabase mongodatabase = mongoclient.getdatabase (dbName);        mongocollection<document> collectiondocuments = Mongodatabase.getcollection (collection);    if (null = = collectiondocuments) return null;    return collectiondocuments;      }/** * Get to Mongoclient * @param IP * @param port * @param userName * @param dbName * @param PSW * @returnMongoClient */public static mongoclient getmongoclientbycredential (String ip,int port,string Usernam        E,string dbname,string psw) {serveraddress serveraddress = new ServerAddress (ip,port);        list<serveraddress> Addrs = new arraylist<serveraddress> ();        Addrs.add (serveraddress); Mongocredential.createscramsha1credential () Three parameters for user name Database name password mongocredential credential = Mongocredential.crea        Tescramsha1credential (UserName, DbName, Psw.tochararray ());        List<mongocredential> credentials = new arraylist<mongocredential> ();        Credentials.add (credential);        Get MongoDB connection via connection authentication mongoclient mongoclient = new Mongoclient (addrs,credentials);    return mongoclient;     }/** * Insert document DATA * @param mongocollection * @param params*/public void Insertdoucument (final mongocollection<document> mongocollection, final map<string,object> p            Arams) {if (null = = Mongocollection) {logger.info (no_found_mongo_collection);        Return            } try {Document document = new document ();            Params.keyset (). Stream (). ForEach (field, Params.get (field)), Document.append (field);            list<document> documents = new arraylist<> ();            Documents.Add (document);            Mongocollection.insertmany (documents);        Logger.info (INSERT_DOCUMEN_SUCCESSS);            }catch (Exception e) {e.printstacktrace ();        Logger.error (insert_documen_exception); }}/** * Update document * @param mongocollection * @param conditionparams * @param updateparams */Pub LIC void UpdateDocument (final mongocollection<document> mongocollection,final map<string,object>                        Conditionparams,       Final map<string,object> updateparams,final Boolean multiupdate) {if (null = = Mongocollection) retu        Rn        if (null = = Conditionparams) return;        if (null = = Updateparams) return;        Document conditondocument = new document (); Conditionparams.keyset (). Stream (). filter (p, null! = P). ForEach (o, {conditondocument.append (O,conditi        Onparams.get (o));        });        Document UpdateDocument = new document (); Updateparams.keyset (). Stream (). filter (p, null! = P). ForEach (o, {updatedocument.append (o,updateparams        . Get (o));        });        Updateresult updateresult = null; if (multiupdate) {//whether bulk update Updateresult = Mongocollection.updatemany (conditondocument,new Document ("$set", Updat        Edocument));        }else {updateresult = Mongocollection.updateone (conditondocument,new Document ("$set", updatedocument)); } System.out.println ("Modified:" +updateresult.getmodifiedcount () + " Data ");      }/** * Condition Delete Document If multiple deletions * @param mongocollection * @param multiple * @param conditionparams * @return                               */Public long deletedocument (final mongocollection<document> mongocollection,final boolean multiple,        Final map<string,object> Conditionparams) {if (null = = Mongocollection) return 0;        if (null = = Conditionparams) return 0;        Document document = new document (); Conditionparams.keyset (). Stream (). filter (p, null! = P). ForEach (o, {document.append (o,conditionparams        . Get (o));        });        if (multiple) {return Mongocollection.deletemany (document). Getdeletedcount ();    }//Delete document first return Mongocollection.deleteone. Getdeletedcount (); /** * Query document with conditions, range lookup, sorting, paging * @param mongocollection * @param conditionparams * @param limit * @par AM Skip * @param sortparams * * Public finditerable<documenT> querydocument (Final mongocollection<document> mongocollection, final map<string,object> Conditionparams, final string op,final string Comparefield, Final map<st Ring,integer> gtltorotherparams, Final map<string,object> Sortpara ms,final integer skip,final integer limit) {if (null = = Mongocollect        ION) return null;        finditerable<document> finditerable = Mongocollection.find ();        Document conditiondocument = new document ();        Document comparedocument = new document ();                if (null! = Conditionparams && null! = finditerable) {Conditionparams.foreach ((k,v)->{                if (Stringutils.isnotblank (k)) {conditiondocument.append (k,v);            }            });            finditerable = Finditerable.filter (conditiondocument); Mongocursor<document> mongocursor = Finditerable.iterator ();            while (Mongocursor.hasnext ()) {System.out.println ("conditional filtering--" +mongocursor.next ()); }} if (null! = finditerable && null! = gtltorotherparams) {Document Gtorltdoc = new Docum            ENT ();            Gtltorotherparams.foreach ((k,v), {if (Stringutils.isnotblank (k)) Gtorltdoc.append (K,V);            });            Comparedocument = new Document (Comparefield,gtorltdoc);        finditerable = Finditerable.filter (new Document (comparefield,comparedocument)); if (Stringutils.isnotblank (OP)) {if ("and". Equals (OP)) {finditerable = mongocollection.            Find (Filters.and (conditiondocument,comparedocument)); }else if ("or". Equals (OP)) {finditerable = Mongocollection.find (filters.or (conditiondocument,comparedocument            )); }else if ("not". Equals (OP)) {//exclusion range finditerable = MONGOCollection.find (Filters.and (Conditiondocument,filters.not (comparedocument)));        }else{//default is and query finditerable = Mongocollection.find (Filters.and (conditiondocument,comparedocument));        } mongocursor<document> MongoCursor3 = Finditerable.iterator ();        while (Mongocursor3.hasnext ()) {System.out.println (op+ "Filter-and" +mongocursor3.next ());            } if (null! = sortparams) {Document sortdocument = new Document (); Sortparams.foreach ((k,v)->{if (Stringutils.isnotblank (k)) {Sortdocument.append (k,v                );            }            });            finditerable = Finditerable.sort (sortdocument);            mongocursor<document> MongoCursor2 = Finditerable.iterator ();            while (Mongocursor2.hasnext ()) {System.out.println ("sort--" +mongocursor2.next ());            }} if (null! = finditerable && null! = limit) {finditerable = Finditerable.limit (limit);        } if (null! = finditerable && null! = Skip) {finditerable = Finditerable.skip (skip);    } return finditerable; }/** * in query * @param mongocollection * @return * */public finditerable<document> Querydocumen TIn (Final mongocollection<document> mongocollection,string field, list<string> List) {if (null = = Mo        Ngocollection) return null;        finditerable<document> finditerable = mongocollection.find (New document (Field,new document ("$in", list));    return finditerable; /** * Full-text query * @param mongocollection * @return * */public finditerable<document> Querydocumen        T (final mongocollection<document> mongocollection) {if (null = = mongocollection) return null;        finditerable<document> finditerable = Mongocollection.find ();    return finditerable; /** * Query Document Simple condition query * @param mOngocollection * @param conditionparams * @return * */Public finditerable<document> querydocument (FINA L mongocollection<document> mongocollection, final map<string,object> conditionparams) {if (null = =        Mongocollection) return null;        finditerable<document> finditerable = Mongocollection.find ();        if (null = = Conditionparams | | null = finditerable) return finditerable;        Document document = new document ();            Conditionparams.foreach ((k,v)->{if (Stringutils.isnotblank (k)) {document.append (k,v);        }        });        finditerable = Finditerable.filter (document);    return finditerable; /** * column information for output section * @param documents */public static void Printdocuments (finditerable<document>            Documents, string[] fields} {if (Fields! = null && fields.length > 0) {int num = 0; for (Document d:documents) {StRingbuilder StringBuilder = new StringBuilder ();                    for (int i = 0; i < fields.length; i++) {/*if (Fields[i].equals ("CATM")) {}*/                Stringbuilder.append (Fields[i] + ":" +d.getstring (Fields[i]) + "");            } System.out.println ("+ (++num) +" bar data: "+ StringBuilder);            }}else{for (Document d:documents) {System.out.println (d.tostring ()); }}}/** * to output all column information * @param documents */public void printdocuments (Finditerable<docume        nt> documents) {int num = 0;        for (Document d:documents) {System.out.println ("+ (++num) +" bar data: "+ d.tostring ()); }    }}

  

MONGO used to define the comparison constants
public enum Mongoconst {    GT ("$gt"),    LT ("$lt"),    GTE ("$gte"),    LTE ("$lte"), and ("and    "),    OR (" or "), not    (' not ');    Private String compareidentify;    Mongoconst (String compareidentify) {        this.compareidentify = compareidentify;    }    Public String getcompareidentify () {        return compareidentify;    }}

  

Test classes for Tool classes
Package Test;import Utils.mongoconst;import Utils.mongodbutil;import com.google.common.collect.lists;import Com.google.common.collect.maps;import Com.mongodb.mongoclient;import Com.mongodb.client.finditerable;import Com.mongodb.client.mongocollection;import Org.bson.document;import Java.util.hashmap;import Java.util.List;import Java.util.map;public class MongoTest02 {public static void main (string[] args) {Mongodbutil mongodbutil = Mong        Odbutil.getmongodbutilinstance ();        Mongoclient meiyaclient = mongodbutil.getmongoclientbycredential ("127.0.0.1", 27017, "my", "my", "my");            try {mongocollection<document> collection = Mongodbutil.getmongocollection (meiyaclient, "test", "hobby");               map<string,object> insert = new hashmap<> ();            1, test Increase/* Insert.put ("name", "Zy");            Insert.put ("Age", "12");            Insert.put ("date", "2018-04-02t09:44:02.658+0000");            Insert.put ("School", "Xiamen Polytechnic"); MOngodbutil.insertdoucument (Collection,insert); *//2, test conditions, range, sort query/* map<string,object> Conditi            ONS = Maps.newhashmap ();            Conditions.put ("name", "Zhang Yuan");            Map<string,integer> compares = Maps.newhashmap ();            Compares.put (MongoConst.GT.getCompareIdentify (), 20);            Compares.put (MongoConst.LTE.getCompareIdentify (), 28);            String Opand = MongoConst.AND.getCompareIdentify ();            map<string,object> sortparams = Maps.newhashmap ();            Sortparams.put ("Age",-1); finditerable<document> documents = mongodbutil.querydocument (Collection,null,opand, "age", compares,            sortparams,null,2); Mongodbutil.printdocuments (documents); *//3, in query/*list<string> names = Lists.newarraylist ("Zhang Yuan            "," Zy "," Zyy ");            finditerable<document> documents = Mongodbutil.querydocumentin (collection, "name", names);         Mongodbutil.printdocuments (documents); * *   4 bulk Delete/*map<string,object> conditionparams = Maps.newhashmap ();            Conditionparams.put ("School", "Xiamen Polytechnic");            Long Count = Mongodbutil.deletedocument (collection,true,conditionparams);            System.out.println (count); *//update map<string,object> queryparams = Maps.newhashmap ();            Queryparams.put ("School", "Modified school");            map<string,object> updateparams = Maps.newhashmap ();            Updateparams.put ("name", "Modified name");        Mongodbutil.updatedocument (Collection,queryparams,updateparams,false);        } catch (Exception e) {System.err.println (E.getclass (). GetName () + ":" + e.getmessage ()); }    }}

  

MongoDB Tool class and test class "Java"

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.