Java operates on MongoDB fuzzy and paging queries

  • 2020-05-10 18:04:24
  • OfStack

The example of this article is to share the Java operation MongoDB fuzzy query and paging query, for your reference, the specific content is as follows

Fuzzy query conditions:
1. Perfect match
Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE);
2. Right matching
Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE);
3. Left matching
Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE);
4. Fuzzy matching
Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE);
Total record query:
count(), returns the total number of queries.
Query record sorting:
BasicDBObject sort = new BasicDBObject();
sort.put("name",1);
1. Positive order; -1. Represents reverse order
Paging query:
skip(), how many records to skip
limit(), return how many records

Code example:



package com.what21.mongodb.demo;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
 
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
 
public class OperateDemo2 {
 
  /**
   * @return
   * @throws Exception
   */
  public static MongoClient getMongoClient()throws Exception{
    try {
      //===================================================//
      List<ServerAddress> serverList = new ArrayList<ServerAddress>();
      serverList.add(new ServerAddress("192.168.18.85", 27017));
      //===================================================//
      List<MongoCredential> mcList = new ArrayList<MongoCredential>();
      String username = "root";
      String database = "demo";
      char[] password = "root123".toCharArray();
      mcList.add(MongoCredential.createCredential(username, database,password));
      //===================================================//
      MongoClientOptions.Builder builder = MongoClientOptions.builder();
      //  With the target database can be established to the maximum connection The number of 50 
      builder.connectionsPerHost(50); 
      //  If all of the current connection All in use, then each connection You can have on 50 Three threads are queued  
      builder.threadsAllowedToBlockForConnectionMultiplier(50); 
      // 1 Thread access to the database, in the success of the acquisition 1 The maximum wait time before all available database connections is 2 minutes  
      //  It's a little bit dangerous here maxWaitTime If the connection is not obtained, the thread will throw it Exception 
      //  So it's set here maxWaitTime It should be large enough to avoid database access failures due to too many queued threads  
      builder.maxWaitTime(1000*60*2); 
      //  To establish a connection to a database timeout Set to 1 minutes  
      builder.connectTimeout(1000*60*1);  
      //===================================================//
      MongoClientOptions mco = builder.build(); 
      return new MongoClient(serverList, mcList, mco);
    } catch (Exception e) {
      throw e;
    }
  }
   
  /**
   * @param dbname
   * @return
   * @throws Exception
   */
  public static DB getDB(String dbname) throws Exception{
    return getMongoClient().getDB(dbname);
  }
   
  /**
   * @param db
   */
  public static void collections(DB db){
    Set<String> colls = db.getCollectionNames();
    for (String collName : colls) {
      System.out.println(collName);
    }
  }
   
  /**
   *  Record total query 
   * 
   * @param db
   * @param name
   */
  public static void count(DB db,String name){
    DBCollection dbColl = db.getCollection(name);
    int count = dbColl.find().count();
    System.out.println(" A total of:  " + count + " a ");
  }
   
   
  /**
   *  Fuzzy query 
   * 
   * @param db
   * @param name
   */
  public static void query(DB db,String name){
    DBCollection dbColl = db.getCollection(name);
    // An exact match 
    //Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE);
    // The right match 
    //Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE);
    // The left matching 
    //Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE);
    // Fuzzy matching 
    Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE);
    BasicDBObject query = new BasicDBObject();
    query.put("name",pattern);
    BasicDBObject sort = new BasicDBObject();
    // 1, Represents positive order;   - 1, According to reverse 
    sort.put("name",1);
    DBCursor cur = dbColl.find(query).sort(sort);
    int count = 0;
    while (cur.hasNext()) {
      DBObject obj = cur.next();
      System.out.print("name=" + obj.get("name"));
      System.out.print(",email=" + obj.get("email"));
      System.out.println(",passwd=" + obj.get("passwd"));
      count ++;
    }
    System.out.println(" A total of:  " + count + " a ");
  }
   
 
  /**
   *  Paging query 
   * 
   * @param db
   * @param name
   * @param start
   * @param pageSize
   */
  public static void page(DB db,String name,int start,int pageSize){
    DBCollection dbColl = db.getCollection(name);
    BasicDBObject sort = new BasicDBObject();
    sort.put("name",1);
    DBCursor cur = dbColl.find().sort(sort).skip(start).limit(pageSize);;
    int count = 0;
    while (cur.hasNext()) {
      DBObject obj = cur.next();
      System.out.print("name=" + obj.get("name"));
      System.out.print(",email=" + obj.get("email"));
      System.out.println(",passwd=" + obj.get("passwd"));
      count ++;
    }
    System.out.println(" A total of:  " + count + " a ");
  }
  /**
   * @param args
   * @throws Exception 
   */
  public static void main(String[] args) throws Exception {
    DB db = getDB("demo");
    collections(db);
    String name = "users";
    System.out.println("count()=================================================");
    count(db,name);
    System.out.println("query()=================================================");
    query(db,name);
    System.out.println("page()=================================================");
    page(db,name,10, 10);
  }
 
}

The above is Java operation MongoDB fuzzy query and paging query implementation code, I hope to help you learn.


Related articles: