I\'m using mongo-java-driver 3.0.2.
I have a method that uses MongoCollection.aggregate(List
to sort and limit:>
This still works on the 3.0.3 driver:
MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017));
DB test = client.getDB("test");
DBCollection sample = test.getCollection("sample");
List aggregationQuery = Arrays.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);
}
Of course you can also use newer classes as well:
MongoClient client = new MongoClient(new ServerAddress("192.168.2.4", 27017));
MongoDatabase db = client.getDatabase("test");
MongoCollection collection = db.getCollection("sample");
AggregateIterable result = collection.aggregate(Arrays.asList(
new BasicDBObject("$sort", new BasicDBObject("score", -1)),
new BasicDBObject("$limit", 1)
)).allowDiskUse(true);
MongoCursor cursor = result.iterator();
while (cursor.hasNext()) {
Document doc = cursor.next();
System.out.println(doc);
}
So .aggregate() on MongoCollection returns an AggregateIterable class instance, which has an .allowDiskuse() method as well as others to set aggregation options.