This article describes the MongoDB database operation tool class in Java singleton mode. Share it for your reference, as follows:
I often perform some basic operations on MongoDB, and merge these commonly used operations into a tool class for easy development and use.
The use of Spring Data, Morphia and other frameworks is to reduce learning and maintenance costs. In addition, if you directly use JDBC methods, you can be more flexible and leave a footprint for your 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 class 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.MongoCollection;import com.mongodb.client.MongoCollection;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 class Mongo instance represents a database connection pool, even in a multi-threaded environment, a Mongo instance is enough for us<br> * Note that Mongo has implemented a connection pool and is thread-safe. <br> * Designed as singleton mode, because MongoDB's Java driver is thread-safe, for general applications, there is only one Mongo instance, <br> * Mongo has a built-in connection pool (default is 10). For environments with a large number of write and read, in order to ensure that the same DB is used in a Session, <br> * DB and DBCollection are absolutely thread-safe<br> * * @author zhoulingfei * @date 2015-5-29 11:49:49 am * @version 0.0.0 * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved. */public enum MongoDBUtil { /** * Define an enumerated element that represents an instance of this class*/ instance; private MongoClient mongoClient; static { System.out.println("========================================================================================================================================================================================================================================================================================================================================================================================================================================================================= e.printStackTrace(); } // Get attribute value from the configuration file String ip = config.getString("host"); int port = config.getInt("port"); instance.mongoClient = new MongoClient(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.mongoClient = new MongoClient(listHost); // Most users use mongodb under the secure intranet, but if mongodb is set to secure authentication mode, they need to provide the user name and password on the client: // boolean auth = db.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); // options.autoConnectRetry(true); // auto reconnect true // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time options.connectionsPerHost(300);// The connection pool is set to 300 connections, the default is 100 options.connectTimeout(15000);// The connection timeout is recommended >3000ms options.maxWaitTime(5000); // options.socketTimeout(0);// The socket timeout time, 0 unlimited options.threadsAllowedToBlockForConnectionMultiplier(5000);// The number of thread queues, if the connection thread is full, the "Out of semaphores to get db" error will be thrown. options.writeConcern(WriteConcern.SAFE);// options.build(); } // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- database; } return null; } /** * Get collection object - Specify Collection * * @param collName * @return */ public MongoCollection<Document> getCollection(String dbName, String collName) { if (null == collName || "".equals(collName)) { return null; } if (null == dbName || "".equals(dbName)) { return null; } MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName); return collection; } /** * Query all table names under DB*/ public List<String> getAllCollections(String dbName) { MongoIterable<String> colls = getDB(dbName).listCollectionNames(); List<String> _list = new ArrayList<String>(); for (String s : cols) { _list.add(s); } return _list; } /** * Get a list of all database names* * @return */ public MongoIterable<String> getAllDBNames() { MongoIterable<String> s = mongoClient.listDatabaseNames(); return s; } /** * Delete a database*/ public void dropDB(String dbName) { getDB(dbName).drop(); } /** * Find object-based based on the primary key _id * * @param collection * @param id * @return */ public Document findById(MongoCollection<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(MongoCollection<Document> coll) { int count = (int) coll.count(); return count; } /** Conditional query*/ public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) { return coll.find(filter).iterator(); } /** Pagination query*/ public MongoCursor<Document> findByPage(MongoCollection<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(MongoCollection<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(MongoCollection<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, new); // Completely replace coll.updateOne(filter, new Document("$set", newdoc)); return newdoc; } public void dropCollection(String dbName, String collName) { getDB(dbName).getCollection(collName).drop(); } /** * Close Mongodb */ public void close() { if (mongoClient != null) { mongoClient.close(); mongoClient = null; } } /** * Test portal* * @param args */ public static void main(String[] args) { String dbName = "GC_MAP_DISPLAY_DB"; String collName = "COMMUNITY_BJ"; MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName); // Insert multiple pieces // 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 = "556925f34711371df0ddfd4b"; // Document doc = MongoDBUtil2.instance.findById(coll, id); // System.out.println(doc); // Query multiple // MongoCursor<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 // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator(); // Delete the database // MongoDBUtil2.instance.dropDB("testdb"); // Delete the table // MongoDBUtil2.instance.dropCollection(dbName, collName); // Modify data// String id = "556949504711371c60601b5a"; // Document newdoc = new Document(); // newdoc.put("name", "time"); // MongoDBUtil.instance.updateById(coll, id, newdoc); // Statistics table// System.out.println(MongoDBUtil.instance.getCount(coll)); // Query all Bson filter = Filters.eq("count", 0); MongoDBUtil.instance.find(coll, filter); }}For more information about Java related content, please check out the topics of this site: "Summary of Java's skills to operate databases using JDBC", "Summary of Java+MySQL database programming", "Tutorial on Java Data Structure and Algorithm", "Summary of Java File and Directory Operation Skills", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.