This article shares Java operation MongoDB fuzzy query and pagination query for your reference. The specific content is as follows
Fuzzy query conditions:
1. Exact match
Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE);
2. Right match
Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE);
3. Left match
Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE);
4. Fuzzy matching
Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE);
Total records query:
count(), returns the total number of queries.
Query record sorting:
BasicDBObject sort = new BasicDBObject();
sort.put("name",1);
1. Represents positive order; -1. Represents reverse order
Pagination query:
skip(), how many records are skipped
limit(), how many records are returned
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(); // The maximum number of connections that can be created with the target database is 50 builder.connectionsPerHost(50); // If all connections are currently in use, there can be 50 threads queued to wait for builder.threadsAllowedToBlockForConnectionMultiplier(50); // When a thread accesses the database, the maximum waiting time before successfully obtaining an available database connection is 2 minutes. // This is more dangerous. If the connection is not obtained after maxWaitTime, the thread will throw an Exception // Therefore, the maxWaitTime set here should be large enough to avoid database access failure due to excessive queued threads builder.maxWaitTime(1000*60*2); // Set the timeout for establishing a connection with the database to 1 minute 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> cols = db.getCollectionNames(); for (String collName : colls) { System.out.println(collName); } } /** * Query for total records* * @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("Total: " + count + "s"); } /** * Fuzzy query* * @param db * @param name */ public static void query(DB db,String name){ DBCollection dbColl = db.getCollection(name); //Exact match//Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE); //Right match//Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE); //Left match//Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE); //Fuzzy match Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE); BasicDBObject query = new BasicDBObject(); query.put("name",pattern); BasicDBObject sort = new BasicDBObject(); // 1, indicates positive order; -1, indicates reverse order 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("Total: " + count + "items"); } /** * Pagination 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("Total: " + count + "s"); } /** * @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 the implementation code for Java operations MongoDB fuzzy query and pagination query. I hope it will be helpful to everyone's learning.