Tool class:
Package Utils;import Com.google.common.collect.lists;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 Org.bson.conversions.bson;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 MONGO library succeeded"; 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 Mongodbut Il (); } 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 Mongocolle Ction<document> mongocollection, Final map<string,object> params) {if (null = = Mongocollection) return; try {Document document = new document (); Params.keyset (). Stream (). ForEach (field, Params.get (field)), Document.append (field); list<document> documents = Lists.newarraylist (); 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) {if (null = = Mongocollection) return; 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 = Mongocollection.updatemany (conditondocument,new Document ("$set", updatedocument)); System.out.println ("Modified:" +updateresult.getmodifiedcount () + "bar data"); /** * Delete Document * @param mongocollection * @param multiple * @param conditionparams * @return * * Public long deletedocument (final mongocollection<document> mongocollection,final Boolean multiple, Final map<string,object> conditionparams) {if (null = = Mongocollecti ON) 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 range lookup, pagination, sort * @param mongocollection * @param conditionparams * @param limit * @param Skip * @param sortparams */public finditerable<document> querydocument (final mongocollection<document > mongocollection, Final map<string,object> conditionparams, final Integer limit, fin Al Integer Skip, Final map<string,integer> sortparams, Final map<string,integer> gtltorotherparams,final String Comparefield) {if (null = = Mongocollection) return null; finditerable<document> finditerable = Mongocollection.find (); if (null = = Conditionparams | | null = finditerable) return finditerable; Document document = new document (); Conditionparams.keyset (). Stream (). Filter (P-null!=p). ForEach (O-document.append (O,conditionparams.get (o) )); finditerable = Finditerable.filter (document); mongocursor<document> mongocursor = Finditerable.iterator (); while (Mongocursor.hasnext ()) {System.out.println (Mongocursor.next ()); } if (null = = Finditerable | | null = GTLTOROTHERPARAMS) return finditerable; Document Gtorltdoc = new document (); Gtltorotherparams.keyset (). Stream (). Filter (P-null!=p). ForEach (O, Gtorltdoc.append (O, Gtltorotherparams.get (o))); finditerable = Finditerable.filter (NEW Document (Comparefield,gtorltdoc)); if (null = = Finditerable | | null = = limit) return finditerable; finditerable = Finditerable.limit (limit); if (null = = Finditerable | | null = SKIP) return finditerable; finditerable = Finditerable.skip (skip); if (null = = Sortparams) return finditerable; Document sortdocument = new document (); Sortparams.keyset (). Stream (). Filter (P--null!=p). ForEach (O-sortdocument.append (O,sortparams.get (o))); finditerable = Finditerable.filter (sortdocument); mongocursor<document> MongoCursor2 = Finditerable.iterator (); while (Mongocursor2.hasnext ()) {System.out.println (Mongocursor2.next ()); } 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; }/** * with sorted query * @param mongocollection * @param conditionparams * @param limit * @param skip * @param sortparams * @return */public finditerable<document> querydocument (final mongocollection<docum Ent> mongocollection, Final map<string,object> conditionparams, fin Al integer limit, final Integer Skip, final map<string,integer> sortparams) {if (null = = Mongocollection) return null; /** * 1. Gets the iterator finditerable<document> * 2. Gets the cursor mongocursor<document> * 3. Traversal of retrieved document collection by cursor * */finditerable<document> finditerable = Mongocollection.find (); if (null = = Conditionparams | | null = finditerable) return finditerable; Document document = new document (); Conditionparams.keyset (). Stream (). Filter (P-null!=p). ForEach (O-document.append (O,conditionparams.get (o))); finditerable = Finditerable.filter (document); if (null = = Finditerable | | null = = limit) return finditerable; finditerable = Finditerable.limit (limit); if (null = = Finditerable | | null = SKIP) return finditerable; finditerable = Finditerable.skip (skip); if (null = = Sortparams) return finditerable; Document sortdocument = new document (); Sortparams.keyset (). Stream (). Filter (P--null!=p). ForEach (O-sortdocument.append (O,sortparams.get (o))); finditerable = Finditerable.sort (sortdocument); return finditerable; /** * Query Document Simple criteria query * @param mongocollection * @param conditionparams * @return * * Public FindIt Erable<document> querydocument (Final 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.keyset (). Stream (). Filter (P-null!=p). ForEach (O-document.append (O,conditionparams.get (o) )); finditerable = Finditerable.filter (document); return finditerable; /** * column information for output section * @param documents */public void printdocuments (finditerable<document> documen TS, 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); }}}/** * 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 ()); } }}
Test class:
public class Mongo {public static void main (string[] args) {Mongodbutil mongodbutil = mongodbutil.getmongodbut Ilinstance (); Mongoclient client = Mongodbutil.instance (). Getmongoconnect ("127.0.0.1", 27017); Connect local MONGO Mongoclient client = mongodbutil.getmongoclientbycredential ("127.0.0.1", 27017, "my", "my", "my"); try {mongocollection<document> collection = mongodbutil.getmongocollection (client, "whale", "Wb0097waterde Partmentbasic "); 1, simple condition query map<string,object> conditionparams = Maps.newhashmap (); Conditionparams.put ("WBTP", "003"); finditerable<document> documents = mongodbutil.querydocument (collection,conditionparams); Mongodbutil.printdocuments (documents); Insert document for (int i=0;i<=100;i++) {map<string, object> params = Maps.newhashmap (); Params.put ("QQ", "Zy"); Params.put ("Time", New Date ()); Params.put ("name", "BB" + i); Params.put ("num", i); Mongodbutil.insertdoucument (collection, params); }//Change document map<string,object> Condparams = Maps.newhashmap (); Condparams.put ("description", "Database"); Condparams.put ("AA", "BBB"); map<string,object> updateparams = Maps.newhashmap (); Updateparams.put ("description", "Eee"); Mongodbutil.instance (). UpdateDocument (Collection,condparams,updateparams);///delete document data map<string, object> condParams1 = Maps.newhashmap (); Condparams.put ("QQ", 1111);//Mongodbutil.instance (). Deletedocument (COLLECTION,TRUE,CONDPARAMS1); Complex query document map<string,object> CONDPARAMS2 = Maps.newhashmap (); Condparams.put ("QQ", "Zy"); map<string,integer> sortparams = Maps.newhashmap (); Sortparams.put ("num",-1); SortparAms.put ("name", 1); map<string,integer> compareparams = Maps.newhashmap (); Compareparams.put ("$gt", 75); Compareparams.put ("$lt", 83); finditerable<document> documents1 = Mongodbutil.instance (). Querydocument (collection,condparams2,10,0, Sortparams,compareparams, "num"); Mongodbutil.printdocuments (DOCUMENTS1); } catch (Exception e) {System.err.println (E.getclass (). GetName () + ":" + e.getmessage ()); } }}
Own MongoDB's CRUD package