最近在使用 mongoTemplate 进行 skip limit分页查询大量数据很慢,网上推荐使用 DBCursor进行查询
源码地址:
mongoTemplate 使用 DBCursor 进行查询
DBCollection collection = mongoTemplate.getCollection("boundary");
DBCursor cursor = collection.find();
while(cursor.hasNext()){
DBObject obj = cursor.next();
Object object = obj.get("polygons");
..
...
}
我使用的spring-data-mongo 是2.xx.xx以上的,mongoTemplate 是没有 mongoTemplate.getCollection("boundary")方法,
com.mongodb.DBCollection
我们通过查看DBCollection 源码可以看到:
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
DB db = mongoClient.getDB("mydb");
DBCollection collection = db.getCollection("test"); }
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new BasicDBObject("x", 203).append("y", 102));
我们通过mongoTemplate进行获取
DBCollection dbCollection = mongoTemplate.getMongoDbFactory().getLegacyDb().getCollection("xxx");
总体代码如下:
DBCollection dbCollection =
mongoTemplate.getMongoDbFactory().getLegacyDb().getCollection("xxx");
DBCursor cursor = collection.find();
while(cursor.hasNext()){
DBObject obj = cursor.next();
Object object = obj.get("polygons");
..
...
}
最后: 查询的效率我暂时还没跑,先不做评论,也不知道这么整对不对