这仍然适用于3.0.3驱动程序:
MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017)); DB test = client.getDB("test"); DBCollection sample = test.getCollection("sample"); List<DBObject> aggregationQuery = Arrays.<DBObject>asList( new BasicDBObject("$sort",new BasicDBObject("score",-1)), new BasicDBObject("$limit",1) ); System.out.println(aggregationQuery); Cursor aggregateOutput = sample.aggregate( aggregationQuery, AggregationOptions.builder() .allowDiskUse(true) .build() ); while ( aggregateOutput.hasNext() ) { DBObject doc = aggregateOutput.next(); System.out.println(doc); }当然,您也可以使用更新的类:
MongoClient client = new MongoClient(new ServerAddress("192.168.2.4", 27017)); MongoDatabase db = client.getDatabase("test"); MongoCollection<document> collection = db.getCollection("sample"); AggregateIterable<document> result = collection.aggregate(Arrays.asList( new BasicDBObject("$sort", new BasicDBObject("score", -1)), new BasicDBObject("$limit", 1) )).allowDiskUse(true); MongoCursor<document> cursor = result.iterator(); while (cursor.hasNext()) { document doc = cursor.next(); System.out.println(doc); }因此,
.aggregate()在MongoCollection上返回一个
AggregateIterable类实例,该实例具有一个
.allowDiskuse()方法以及其他设置聚合选项的方法。



