服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java操作MongoDB模糊查询和分页查询

Java操作MongoDB模糊查询和分页查询

2020-04-22 11:34java教程网 JAVA教程

这篇文章主要介绍了Java操作MongoDB模糊查询和分页查询的相关资料,需要的朋友可以参考下

本文实例为大家分享了Java操作MongoDB模糊查询和分页查询,供大家参考,具体内容如下

模糊查询条件:
1、完全匹配
Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE);
2、右匹配
Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE);
3、左匹配
Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE);
4、模糊匹配
Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE);
记录总数查询:
count(),返回查询总数。
查询记录排序:
BasicDBObject sort = new BasicDBObject();
sort.put("name",1);
1、表示正序;-1.表示倒序
分页查询:
skip(),跳过多少条记录
limit(),返回多少条记录

代码实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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();
      // 与目标数据库能够建立的最大connection数量为50
      builder.connectionsPerHost(50);
      // 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
      builder.threadsAllowedToBlockForConnectionMultiplier(50);
      // 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
      // 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
      // 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
      builder.maxWaitTime(1000*60*2);
      // 与数据库建立连接的timeout设置为1分钟
      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);
    }
  }
   
  /**
   * 记录总数查询
   *
   * @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("共有: " + count + "个");
  }
   
   
  /**
   * 模糊查询
   *
   * @param db
   * @param name
   */
  public static void query(DB db,String name){
    DBCollection dbColl = db.getCollection(name);
    //完全匹配
    //Pattern pattern = Pattern.compile("^name$", Pattern.CASE_INSENSITIVE);
    //右匹配
    //Pattern pattern = Pattern.compile("^.*name$", Pattern.CASE_INSENSITIVE);
    //左匹配
    //Pattern pattern = Pattern.compile("^name.*$", Pattern.CASE_INSENSITIVE);
    //模糊匹配
    Pattern pattern = Pattern.compile("^.*name8.*$", Pattern.CASE_INSENSITIVE);
    BasicDBObject query = new BasicDBObject();
    query.put("name",pattern);
    BasicDBObject sort = new BasicDBObject();
    // 1,表示正序; -1,表示倒序
    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("共有: " + count + "个");
  }
   
 
  /**
   * 分页查询
   *
   * @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("共有: " + count + "个");
  }
  /**
   * @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);
  }
 
}

以上就是Java操作MongoDB模糊查询和分页查询的实现代码,希望对大家的学习有所帮助。

延伸 · 阅读

精彩推荐