MongoDB Java driver 3.x: How to pass allowDiskUse=true to aggregate() method? -


i'm using mongo-java-driver 3.0.2.

i have method uses mongocollection.aggregate(list<bson> pipeline) sort , limit:

private static mongoiterable<document> selecttop(int n) {     basicdbobject sortfields = new basicdbobject("score", -1);     basicdbobject sort = new basicdbobject("$sort", sortfields);      basicdbobject limit = new basicdbobject("$limit", n);      list<basicdbobject> pipeline = new arraylist<>();     pipeline.add(sort);     pipeline.add(limit);      return playerscollection.aggregate(pipeline); } 

when n big, fails with:

com.mongodb.mongocommandexception: command failed error 16820: 'exception: sort exceeded memory limit of 104857600 bytes, did not opt in external sorting. aborting operation. pass allowdiskuse:true opt in.' 

i've found mongodb shell provides method db.collection.aggregate(pipeline, options) (link) options can contain allowdiskuse field.

i can't find equivalent in java api. although there aggregationoptions class, mongocollection class doesn't provide aggregate(list<bson> pipeline, aggregationoptions options) method.

this still works on 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<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);     } 

of course can use newer classes well:

    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);     } 

so .aggregate() on mongocollection returns aggregateiterable class instance, has .allowdiskuse() method others set aggregation options.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -