mongodb分页查询
我们知道mongDB分页查询有两个方法,Limit与Skip方法
MongoDB Limit() 方法
如果你需要在MongoDB中读取指定数量的数据记录,可以使用MongoDB的Limit方法
limit()方法接受一个数字参数,该参数指定从MongoDB中读取的记录条数。
语法
脚本中limit()方法基本语法如下所示:
db.country.find().limit(NUMBER)
java代码实现如下:
// 获取前30条记录
public static void getDataLimit() {
MongoCollection<Document> collection = getMongoCollection();
int number = 30;
FindIterable<Document> result = collection.find().limit(number);
printDocument(result);
}
MongoDB Skip() 方法
我们除了可以使用limit()方法来读取指定数量的数据外,还可以使用skip()方法来跳过指定数量的数据
skip方法同样接受一个数字参数作为跳过的记录条数。
语法
skip() 方法脚本语法格式如下:
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
示例:
db.country.find().limit(30).skip(1)
java代码实现:
// 从第二条记录开始,获取30条记录
public static void getDataLimitSkip() {
MongoCollection<Document> collection = getMongoCollection();
int numberLinit = 30;
int numberSkip = 1;
FindIterable<Document> result = collection.find().limit(numberLinit).skip(numberSkip);
printDocument(result);
}
printDocument(result)方法实现:
/**
* 通过游标遍历检索出的文档集合
*
* @param mongoCursor
*/
public static void printDocument(FindIterable<Document> findIterable) {
// 获取游标MongoCursor<Document>
MongoCursor<Document> mongoCursor = findIterable.iterator();
// 通过游标遍历检索出的文档集合
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
}
全部完整代码:
package com.adtec.mongodb;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.bson.Document;
import org.bson.conversions.Bson;
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.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
/**
*
* @author 浪丶荡
*
*/
public class MongoDBUtils {
public static void main(String[] args) {
// 获取所有文档,打印
// getAllData();
获取记录总数
// getDataSum();
// getXianOfHeBei();
// query(getDB("test"), "country");
getDataLimit();
System.out.println("------------------------------------");
getDataLimitSkip();
}
/**
* 获取集合连接
*
* @return MongoCollection<Document>
*/
public static MongoCollection<Document> getMongoCollection() {
// 连接到 mongodb 服务
String host = "192.168.71.193";
int port = 27017;
@SuppressWarnings("resource")
MongoClient mongoClient = new MongoClient(host, port);
// 连接到数据库
String databaseName = "test";
MongoDatabase database = mongoClient.getDatabase(databaseName);
// 选择集合(类似选择表)
String collectionName = "country";
MongoCollection<Document> collection = database.getCollection(collectionName);
return collection;
}
// 获取DB对象
public static DB getDB(String dbname) {
MongoClient mongoClient = new MongoClient("192.168.71.193", 27017);
DB db = mongoClient.getDB(dbname);
return db;
}
// 模糊查询
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("^.*县.*$", Pattern.CASE_INSENSITIVE);
// db.country.find({'name':{$regex:/县/},'sheng':'11','level':3})
BasicDBObject query = new BasicDBObject();
query.put("name", pattern);
query.put("sheng", "11");
query.put("level", 3);
BasicDBObject sort = new BasicDBObject();
// 1,表示正序; -1,表示倒序
sort.put("name", 1);
DBCursor cur = dbColl.find(query).sort(sort);
Iterator<DBObject> iterator = cur.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
/**
* 获取所有文档,打印
*/
public static void getAllData() {
MongoCollection<Document> collection = getMongoCollection();
// 获取迭代器FindIterable<Document>
FindIterable<Document> findIterable = collection.find();
printDocument(findIterable);
}
/**
* 通过游标遍历检索出的文档集合
*
* @param mongoCursor
*/
public static void printDocument(FindIterable<Document> findIterable) {
// 获取游标MongoCursor<Document>
MongoCursor<Document> mongoCursor = findIterable.iterator();
// 通过游标遍历检索出的文档集合
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
}
// 获取记录总数
public static void getDataSum() {
MongoCollection<Document> collection = getMongoCollection();
long sum = collection.count();
System.out.println(sum);
}
// 查出河北省的县
// db.country.find({'sheng':'13'})
public static void getXianOfHeBei() {
MongoCollection<Document> collection = getMongoCollection();
Bson filter = new Document("sheng", "13");
FindIterable<Document> result = collection.find(filter);
printDocument(result);
}
// 查出北京的县
// db.country.find({'name':{$regex:/县/},'sheng':'11','level':3})
public static void getXianOfBeiJing() {
MongoCollection<Document> collection = getMongoCollection();
Bson filter = new Document("sheng", "11");
String xian = "县";
Pattern pattern = Pattern.compile("^.*" + xian.trim() + "$", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject();
query.put("name", pattern);
FindIterable<Document> result = collection.find(filter);
printDocument(result);
}
// 获取前30条记录
public static void getDataLimit() {
MongoCollection<Document> collection = getMongoCollection();
int number = 30;
FindIterable<Document> result = collection.find().limit(number);
printDocument(result);
}
// 从第二条记录开始,获取30条记录
public static void getDataLimitSkip() {
MongoCollection<Document> collection = getMongoCollection();
int numberLinit = 30;
int numberSkip = 1;
FindIterable<Document> result = collection.find().limit(numberLinit).skip(numberSkip);
printDocument(result);
}
}
结果:
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Cluster created with settings {hosts=[192.168.71.193:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Opened connection [connectionId{localValue:1, serverValue:18}] to 192.168.71.193:27017
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Monitor thread successfully connected to server with description ServerDescription{address=192.168.71.193:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 5]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=1532285}
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=192.168.71.193:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Opened connection [connectionId{localValue:2, serverValue:19}] to 192.168.71.193:27017
Document{{_id=59ec5362e0781ef646f5ad03, country=China}}
Document{{_id=59ec55aa937ceb812c804c53, code=110000, sheng=11, di=00, xian=00, name=北京市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c54, code=110000, sheng=11, di=00, xian=00, name=北京市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c55, code=110100, sheng=11, di=01, xian=00, name=市辖区, level=2.0}}
Document{{_id=59ec563f937ceb812c804c56, code=110101, sheng=11, di=01, xian=01, name=东城区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c57, code=110102, sheng=11, di=01, xian=02, name=西城区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c58, code=110105, sheng=11, di=01, xian=05, name=朝阳区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c59, code=110106, sheng=11, di=01, xian=06, name=丰台区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5a, code=110107, sheng=11, di=01, xian=07, name=石景山区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5b, code=110108, sheng=11, di=01, xian=08, name=海淀区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5c, code=110109, sheng=11, di=01, xian=09, name=门头沟区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5d, code=110111, sheng=11, di=01, xian=11, name=房山区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5e, code=110112, sheng=11, di=01, xian=12, name=通州区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5f, code=110113, sheng=11, di=01, xian=13, name=顺义区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c60, code=110114, sheng=11, di=01, xian=14, name=昌平区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c61, code=110115, sheng=11, di=01, xian=15, name=大兴区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c62, code=110116, sheng=11, di=01, xian=16, name=怀柔区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c63, code=110117, sheng=11, di=01, xian=17, name=平谷区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c64, code=110200, sheng=11, di=02, xian=00, name=县, level=2.0}}
Document{{_id=59ec563f937ceb812c804c65, code=110228, sheng=11, di=02, xian=28, name=密云县, level=3.0}}
Document{{_id=59ec563f937ceb812c804c66, code=110229, sheng=11, di=02, xian=29, name=延庆县, level=3.0}}
Document{{_id=59ec563f937ceb812c804c67, code=120000, sheng=12, di=00, xian=00, name=天津市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c68, code=120100, sheng=12, di=01, xian=00, name=市辖区, level=2.0}}
Document{{_id=59ec563f937ceb812c804c69, code=120101, sheng=12, di=01, xian=01, name=和平区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6a, code=120102, sheng=12, di=01, xian=02, name=河东区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6b, code=120103, sheng=12, di=01, xian=03, name=河西区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6c, code=120104, sheng=12, di=01, xian=04, name=南开区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6d, code=120105, sheng=12, di=01, xian=05, name=河北区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6e, code=120106, sheng=12, di=01, xian=06, name=红桥区, level=3.0}}
Document{{_id=59ec571a937ceb812c804c6f, code=120110, sheng=12, di=01, xian=10, name=东丽区, level=3.0}}
------------------------------------
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Cluster created with settings {hosts=[192.168.71.193:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=192.168.71.193:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Opened connection [connectionId{localValue:3, serverValue:20}] to 192.168.71.193:27017
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Monitor thread successfully connected to server with description ServerDescription{address=192.168.71.193:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 5]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=1007126}
十一月 22, 2017 10:39:45 上午 com.mongodb.diagnostics.logging.JULLogger log
信息: Opened connection [connectionId{localValue:4, serverValue:21}] to 192.168.71.193:27017
Document{{_id=59ec55aa937ceb812c804c53, code=110000, sheng=11, di=00, xian=00, name=北京市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c54, code=110000, sheng=11, di=00, xian=00, name=北京市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c55, code=110100, sheng=11, di=01, xian=00, name=市辖区, level=2.0}}
Document{{_id=59ec563f937ceb812c804c56, code=110101, sheng=11, di=01, xian=01, name=东城区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c57, code=110102, sheng=11, di=01, xian=02, name=西城区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c58, code=110105, sheng=11, di=01, xian=05, name=朝阳区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c59, code=110106, sheng=11, di=01, xian=06, name=丰台区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5a, code=110107, sheng=11, di=01, xian=07, name=石景山区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5b, code=110108, sheng=11, di=01, xian=08, name=海淀区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5c, code=110109, sheng=11, di=01, xian=09, name=门头沟区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5d, code=110111, sheng=11, di=01, xian=11, name=房山区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5e, code=110112, sheng=11, di=01, xian=12, name=通州区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c5f, code=110113, sheng=11, di=01, xian=13, name=顺义区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c60, code=110114, sheng=11, di=01, xian=14, name=昌平区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c61, code=110115, sheng=11, di=01, xian=15, name=大兴区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c62, code=110116, sheng=11, di=01, xian=16, name=怀柔区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c63, code=110117, sheng=11, di=01, xian=17, name=平谷区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c64, code=110200, sheng=11, di=02, xian=00, name=县, level=2.0}}
Document{{_id=59ec563f937ceb812c804c65, code=110228, sheng=11, di=02, xian=28, name=密云县, level=3.0}}
Document{{_id=59ec563f937ceb812c804c66, code=110229, sheng=11, di=02, xian=29, name=延庆县, level=3.0}}
Document{{_id=59ec563f937ceb812c804c67, code=120000, sheng=12, di=00, xian=00, name=天津市, level=1.0}}
Document{{_id=59ec563f937ceb812c804c68, code=120100, sheng=12, di=01, xian=00, name=市辖区, level=2.0}}
Document{{_id=59ec563f937ceb812c804c69, code=120101, sheng=12, di=01, xian=01, name=和平区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6a, code=120102, sheng=12, di=01, xian=02, name=河东区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6b, code=120103, sheng=12, di=01, xian=03, name=河西区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6c, code=120104, sheng=12, di=01, xian=04, name=南开区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6d, code=120105, sheng=12, di=01, xian=05, name=河北区, level=3.0}}
Document{{_id=59ec563f937ceb812c804c6e, code=120106, sheng=12, di=01, xian=06, name=红桥区, level=3.0}}
Document{{_id=59ec571a937ceb812c804c6f, code=120110, sheng=12, di=01, xian=10, name=东丽区, level=3.0}}
Document{{_id=59ec571a937ceb812c804c70, code=120111, sheng=12, di=01, xian=11, name=西青区, level=3.0}}