MongoDB database manipulation tool class in Java singleton mode

  • 2020-12-18 01:48:38
  • OfStack

This article gives an example of the MongoDB database manipulation tool class in Java singleton mode. To share for your reference, the details are as follows:

I often do some basic operations on MongoDB and combine these common operations into one tool class for my own development and use.

Spring Data, Morphia and other frameworks are not used in order to reduce learning and maintenance costs. In addition, if you use JDBC directly, you can be more flexible and leave a footprint for your future accumulation.

JAVA Driver version:


<!-- MongoDB drive  -->
<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.0.2</version>
</dependency>

The utility 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.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
/**
 * MongoDB Utility class  Mongo The example represents 1 A pool of database connections, even in a multithreaded environment, 1 a Mongo Examples are enough for us <br>
 *  Pay attention to Mongo Connection pooling has been implemented and is thread-safe.  <br>
 *  Designed as a singleton,   Due to the  MongoDB the Java Drivers are thread-safe, for 1 Like applications, as long as 1 a Mongo An instance is enough, <br>
 * Mongo There is a built-in connection pool (default is 10 A)   For environments where there is a lot of write and read, make sure that the 1 a Session The use of the same 1 a DB When, <br>
 * DB and DBCollection Is absolutely thread-safe <br>
 *
 * @author zhoulingfei
 * @date 2015-5-29  In the morning 11:49:49
 * @version 0.0.0
 * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved.
 */
public enum MongoDBUtil {
  /**
   *  define 1 An enumeration of the elements that represents this class 1 An instance 
   */
  instance;
  private MongoClient mongoClient;
  static {
    System.out.println("===============MongoDBUtil Initialize the ========================");
    CompositeConfiguration config = new CompositeConfiguration();
    try {
      config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
    } catch (ConfigurationException e) {
      e.printStackTrace();
    }
    //  Gets the property 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 Both are under the safe inside network, but if will mongodb Set to security authentication mode, you need to provide the user name and password on the client side: 
    // boolean auth = db.authenticate(myUserName, myPassword);
    Builder options = new MongoClientOptions.Builder();
    // options.autoConnectRetry(true);//  Automatic reconnection true
    // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
    options.connectionsPerHost(300);//  Connection pool is set to 300 A connection , The default is 100
    options.connectTimeout(15000);//  Connection timeout, recommended >3000 ms 
    options.maxWaitTime(5000); //
    options.socketTimeout(0);//  Socket timeout, 0 unlimited 
    options.threadsAllowedToBlockForConnectionMultiplier(5000);//  Number of thread queues, which will be thrown if the connection threads are lined up. Out of semaphores to get db "Error. 
    options.writeConcern(WriteConcern.SAFE);//
    options.build();
  }
  // ------------------------------------ Common methods ---------------------------------------------------
  /**
   *  To obtain DB The instance  -  The specified DB
   *
   * @param dbName
   * @return
   */
  public MongoDatabase getDB(String dbName) {
    if (dbName != null && !"".equals(dbName)) {
      MongoDatabase database = mongoClient.getDatabase(dbName);
      return database;
    }
    return null;
  }
  /**
   *  To obtain collection object  -  The specified 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;
  }
  /**
   *  The query DB All table names below 
   */
  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;
  }
  /**
   *  Gets a list of all database names 
   *
   * @return
   */
  public MongoIterable<String> getAllDBNames() {
    MongoIterable<String> s = mongoClient.listDatabaseNames();
    return s;
  }
  /**
   *  delete 1 A database 
   */
  public void dropDB(String dbName) {
    getDB(dbName).drop();
  }
  /**
   *  To find the object  -  According to 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;
  }
  /**  count  */
  public int getCount(MongoCollection<Document> coll) {
    int count = (int) coll.count();
    return count;
  }
  /**  Conditions of the query  */
  public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
    return coll.find(filter).iterator();
  }
  /**  Paging 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();
  }
  /**
   *  through ID delete 
   *
   * @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, newdoc); //  replace 
    coll.updateOne(filter, new Document("$set", newdoc));
    return newdoc;
  }
  public void dropCollection(String dbName, String collName) {
    getDB(dbName).getCollection(collName).drop();
  }
  /**
   *  Shut down Mongodb
   */
  public void close() {
    if (mongoClient != null) {
      mongoClient.close();
      mongoClient = null;
    }
  }
  /**
   *  Test the entrance 
   *
   * @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 
    // 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);
    // }
    // //  According to the ID The query 
    // 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 database 
    // MongoDBUtil2.instance.dropDB("testdb");
    //  Delete table 
    // MongoDBUtil2.instance.dropCollection(dbName, collName);
    //  Modify the data 
    // String id = "556949504711371c60601b5a";
    // Document newdoc = new Document();
    // newdoc.put("name", " when ");
    // MongoDBUtil.instance.updateById(coll, id, newdoc);
    //  statistics 
    // System.out.println(MongoDBUtil.instance.getCount(coll));
    //  Query all 
    Bson filter = Filters.eq("count", 0);
    MongoDBUtil.instance.find(coll, filter);
  }
}

More about java related content interested readers to view this site project: Java use JDBC database operation skills summary, the summary Java + MySQL database programming, "Java data structure and algorithm tutorial", "Java file and directory skills summary", "Java DOM node operation skills summary" and "Java caching skills summary"

I hope this article has been helpful in java programming.


Related articles: