我在我的代碼中執行以下業務邏輯
Cursor cursor = db.getCollection(CollectionInfo.ORDER).aggregate(pipelines, options);
while (cursor.hasNext()) {
orders.add(new Order(cursor.next().toMap()));
}
return orders;
所以只是為了構建我遍歷所有檔案的物件。所以如果我有很多檔案作為聚合的結果。迭代需要很多時間。有沒有更好的方法來做到這一點?使用 Spring 資料 mongo DB 還是其他任何東西?
uj5u.com熱心網友回復:
使用mongoTemplate.aggregate(...).getMappedResults()
@Autowired
protected MongoTemplate mongoTemplate;
...
List<AggregationOperation> pipeline = ...;
Aggregation agg = Aggregation.newAggregation(pipeline)
.withOptions(...);
List<Orders> orders = mongoTemplate.aggregate(agg, CollectionInfo.ORDER, Order.class)
.getMappedResults();
注意:如果您的查詢回傳超過 1K 個檔案,建議使用$skip/$limit
偽代碼
skip = 0
limit = 1_000
size = 0
do {
//Add skip / limit (do not insert these stages more than once)
pipeline.add(Aggregation.skip(skip))
pipeline.add(Aggregation.limit(limit))
//aggregate
result = mongoTemplate.aggregate(...).getMappedResults();
size = result.size();
skip = limit;
// If there are 1_000 results, probably there are more items, keep iterating
} while(size == limit);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396466.html
標籤:爪哇 MongoDB spring-data-mongodb
下一篇:如何使用聚合確定用戶收集了多少點
