2016-11-18 345 views
1

當前我在春季使用mongoDB作爲mongoTemplate。如何在彈簧中設置allowDiskUse:true mongoTemplate

public List<BasicDBObject> getMoviesByName() { 
    Aggregation aggregation = newAggregation(unwind("movies"), 
      match(where("movies.language").is("english")), 
      sort(Sort.Direction.DESC, "createDate"), 
      group(fields().and("_id", "$_id").and("category", "$category")).push("$movies").as("movies"), 
      project(fields().and("category", "$category").and("movies", "$movies")).andExclude("_id")); 
    AggregationResults<BasicDBObject> groupResults = mongoTemplate.aggregate(
      aggregation, "movieCollection", BasicDBObject.class); 
    return groupResults.getMappedResults(); 
} 

我得到異常

com.mongodb.CommandFailureException: { "serverUsed" : "XXX.XXX.XX.XX:27017" , "errmsg" : "exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in." , "code" : 16819 , "ok" : 0.0} 

我研究過一些帖子allowDiskUse:真正的解決方案,我已經嘗試設置爲true,但沒有結果。請告訴我如何爲上面的代碼

設置
+1

聚合選項你試過'AggregationResults groupResults = mongoTemplate.aggregate( 聚集, 「movieCollection」,BasicDBObject .class).withOptions(newAggregationOptions()。allowDiskUse(true).build());'? – chridam

+0

我已經嘗試了上面的代碼,但沒有結果 –

回答

0

你可以像下面這樣做。

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

//rest of the code 

或者乾脆

Aggregation aggregation = newAggregation(…). 
     withOptions(newAggregationOptions(). 
     allowDiskUse(true).build()); 
0

您可以設置類似

Aggregation aggregation = newAggregation(…).withOptions(Aggregation.newAggregationOptions(). 
         allowDiskUse(true).build());