Java Singleton MongoDB Tool

Source: Internet
Author: User

Java Singleton MongoDB Tool

I often perform some basic operations on MongoDB and merge these common operations into a tool class for self-development and use.

The framework such as Spring Data and Morphia is useless to reduce learning and maintenance costs. In addition, the direct JDBC method can be more flexible, leaving a footprint for future accumulation.

JAVA driver version:

<! -- MongoDB driver -->
<Dependency>
<GroupId> org. mongodb </groupId>
<ArtifactId> mongo-java-driver </artifactId>
<Version> 3.0.2 </version>
</Dependency>

The tool code is as follows:

Package utils;

Import java. util. ArrayList;
Import java. util. List;

Import org. apache. commons. configuration. CompositeConfiguration;
Import org. apache. commons. configuration. ConfigurationException;
Import org. apache. commons. configuration. PropertiesConfiguration;
Import org. bson. Document;
Import org. bson. conversions. Bson;
Import org. bson. types. ObjectId;

Import com. mongodb. BasicDBObject;
Import com. mongodb. MongoClient;
Import com. mongodb. MongoClientOptions;
Import com. mongodb. MongoClientOptions. Builder;
Import com. mongodb. WriteConcern;
Import com. mongodb. client. Collections collection;
Import com. mongodb. client. MongoCursor;
Import com. mongodb. client. MongoDatabase;
Import com. mongodb. client. MongoIterable;
Import com. mongodb. client. model. Filters;
Import com. mongodb. client. result. DeleteResult;

/**
* MongoDB tool Mongo instances represent a database connection pool. Even in a multi-threaded environment, a Mongo instance is sufficient for us. <br>
* Note that Mongo has implemented the connection pool and is thread-safe. <Br>
* Designed as the singleton mode, because the MongoDB Java driver is thread-safe, for general applications, only one Mongo instance is required. <br>
* Mongo has a built-in connection pool (10 by default). For environments with a large number of writes and reads, to ensure that the same database is used in a Session, <br>
* DB and DBCollection are absolutely thread-safe. <br>
*
* @ Author zhoulingfei
* @ Date 11:49:49 AM
* @ Version 0.0.0
* @ Copyright (c) 1997-2015 NavInfo Co. Ltd. All Rights Reserved.
*/
Public enum MongoDBUtil {

/**
* Defines an enumeration element, which represents an instance of this type.
*/
Instance;

Private Guest client guest client;

Static {
System. out. println ("=================== MongoDBUtil initialization ========================= ==== ");
CompositeConfiguration config = new CompositeConfiguration ();
Try {
Config. addConfiguration (new PropertiesConfiguration ("mongodb. properties "));
} Catch (ConfigurationException e ){
E. printStackTrace ();
}
// Obtain the attribute value from the configuration file
String ip = config. getString ("host ");
Int port = config. getInt ("port ");
Instance. Consumer Client = new Consumer Client (ip, port );

// Or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
// List <ServerAddress> listHost = Arrays. asList (new ServerAddress ("localhost", 27017), new ServerAddress ("localhost", 27018 ));
// Instance. Consumer Client = new Consumer Client (listHost );

// Most users use mongodb in the Secure Intranet. However, if you set mongodb as the Security Authentication mode, you need to provide the user name and password on the client:
// Boolean auth = db. authenticate (myUserName, myPassword );
Builder options = new vertex clientoptions. Builder ();
// Options. autoConnectRetry (true); // automatically reconnect to true
// Options. maxAutoConnectRetryTime (10); // the maximum auto connect retry time
Options. connectionsPerHost (300); // set the connection pool to 300 connections. The default value is 100.
Options. connectTimeout (15000); // The connection times out. We recommend that you set the value to 3000 milliseconds.
Options. maxWaitTime (5000 );//
Options. socketTimeout (0); // socket timeout, 0 Unlimited
Options. threadsAllowedToBlockForConnectionMultiplier (5000); // Number of thread queues. If the connection thread is full, the error "Out of semaphores to get db" will be thrown.
Options. writeConcern (WriteConcern. SAFE );//
Options. build ();
}

// -------------------------------------- Sharing method ---------------------------------------------------
/**
* Get DB instance-specify DB
*
* @ Param dbName
* @ Return
*/
Public writable database getDB (String dbName ){
If (dbName! = Null &&! "". Equals (dbName )){
Relational database = relational client. getDatabase (dbName );
Return database;
}
Return null;
}

/**
* Get collection object-specify Collection
*
* @ Param collName
* @ Return
*/
Public Collections collection <Document> getCollection (String dbName, String collName ){
If (null = collName | "". equals (collName )){
Return null;
}
If (null = dbName | "". equals (dbName )){
Return null;
}
Using collection <Document> collection = using client. getDatabase (dbName). getCollection (collName );
Return collection;
}

/**
* Query all table names in the database
*/
Public List <String> getAllCollections (String dbName ){
MongoIterable <String> colls = getDB (dbName). listCollectionNames ();
List <String> _ list = new ArrayList <String> ();
For (String s: colls ){
_ List. add (s );
}
Return _ list;
}

/**
* Retrieve the list of all database names
*
* @ Return
*/
Public writable iterable <String> getAllDBNames (){
MongoIterable <String> s = javasclient. listDatabaseNames ();
Return s;
}

/**
* Delete A Database
*/
Public void dropDB (String dbName ){
GetDB (dbName). drop ();
}

/**
* Search for objects-based on primary key _ id
*
* @ Param collection
* @ Param id
* @ Return
*/
Public Document findById (Collection collection <Document> coll, String id ){
ObjectId _ idobj = null;
Try {
_ Idobj = new ObjectId (id );
} Catch (Exception e ){
Return null;
}
Document myDoc = coll. find (Filters. eq ("_ id", _ idobj). first ();
Return myDoc;
}

/** Statistics */
Public int getCount (distinct collection <Document> coll ){
Int count = (int) coll. count ();
Return count;
}

/** Condition query */
Public writable cursor <Document> find (writable collection <Document> coll, Bson filter ){
Return coll. find (filter). iterator ();
}

/** Query by page */
Public writable cursor <Document> findByPage (collections collection <Document> coll, Bson filter, int pageNo, int pageSize ){
Bson orderBy = new BasicDBObject ("_ id", 1 );
Return coll. find (filter). sort (orderBy). skip (pageNo-1) * pageSize). limit (pageSize). iterator ();
}

/**
* Delete by ID
*
* @ Param coll
* @ Param id
* @ Return
*/
Public int deleteById (Collection collection <Document> coll, String id ){
Int count = 0;
ObjectId _ id = null;
Try {
_ Id = new ObjectId (id );
} Catch (Exception e ){
Return 0;
}
Bson filter = Filters. eq ("_ id", _ id );
DeleteResult deleteResult = coll. deleteOne (filter );
Count = (int) deleteResult. getDeletedCount ();
Return count;
}

/**
* FIXME
*
* @ Param coll
* @ Param id
* @ Param newdoc
* @ Return
*/
Public Document updateById (Collection collection <Document> coll, String id, Document newdoc ){
ObjectId _ idobj = null;
Try {
_ Idobj = new ObjectId (id );
} Catch (Exception e ){
Return null;
}
Bson filter = Filters. eq ("_ id", _ idobj );
// Coll. replaceOne (filter, newdoc); // replaceOne
Coll. updateOne (filter, new Document ("$ set", newdoc ));
Return newdoc;
}

Public void dropCollection (String dbName, String collName ){
GetDB (dbName). getCollection (collName). drop ();
}

/**
* Disable Mongodb
*/
Public void close (){
If (publish client! = Null ){
Using client. close ();
Consumer Client = null;
}
}

/**
* Test entry
*
* @ Param args
*/
Public static void main (String [] args ){

String dbName = "GC_MAP_DISPLAY_DB ";
String collName = "COMMUNITY_BJ ";
Collect collection <Document> coll = MongoDBUtil. instance. getCollection (dbName, collName );

// Insert multiple entries
// For (int I = 1; I <= 4; I ++ ){
// Document doc = new Document ();
// Doc. put ("name", "zhoulf ");
// Doc. put ("school", "NEFU" + I );
// Document interests = new Document ();
// Interests. put ("game", "game" + I );
// Interests. put ("ball", "ball" + I );
// Doc. put ("interests", interests );
// Coll. insertOne (doc );
//}

/// Query by ID
// String id = "536625f000011371df0ddfd4b ";
// Document doc = MongoDBUtil2.instance. findById (coll, id );
// System. out. println (doc );

// Query multiple
// Export cursor <Document> cursor1 = coll. find (Filters. eq ("name", "zhoulf"). iterator ();
// While (cursor1.hasNext ()){
// Org. bson. Document _ doc = (Document) cursor1.next ();
// System. out. println (_ doc. toString ());
//}
// Cursor1.close ();

// Query multiple
// Export cursor <Person> cursor2 = coll. find (Person. class). iterator ();

// Delete the database
// MongoDBUtil2.instance. dropDB ("testdb ");

// Delete a table
// MongoDBUtil2.instance. dropCollection (dbName, collName );

// Modify data
// String id = "536649504711371c60601b5a ";
// Document newdoc = new Document ();
// Newdoc. put ("name", "");
// MongoDBUtil. instance. updateById (coll, id, newdoc );

// Statistical table
// System. out. println (MongoDBUtil. instance. getCount (coll ));

// Query all
Bson filter = Filters. eq ("count", 0 );
Optional dbutil. instance. find (coll, filter );

}

}

Please provide more valuable comments and suggestions.

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.