2017-07-06 5 views
0

aggregateメソッドMongoTemplateAggregationResults<T>を返します。Tはmongoコレクションに対応するクラスです。Spring MongoTemplate - 集計結果をコレクションにマッピングする(リストとマップなど)

場合によっては、特定の基準に応じて、単一のコレクション(プロパティーabc)または2つのプロパティー(pqrおよびxyz)のみをコレクションから取得することもできます。このような場合、コレクション全体をTクラスに取得するか、プロパティ(abc)または(pqr,)を含む新しいクラスを作成することができます。

これらの単一のプロパティをList<String>にマッピングする方法、またはHashMap<String, String>のキーと値のペアとして2つのプロパティをマッピングする方法はありますか?

答えて

2

LinkedHashMapのバックアップ/ Document(2.0.0 spring mongoのバージョン)とjava 8ストリームメソッドを使用してコレクションタイプに解析します。

単一のプロパティ(abc) - リストタイプ

Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("abc")); 
List<String> singleResults = mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getMappedResults().stream().map(item -> item.getString("abc")).collect(Collectors.toList()); 

複数のプロパティ(pqr, xyz) - 地図タイプ

Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("pqr, xyz")); 
List<Map> multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getMappedResults().stream().map (item -> (LinkedHashMap) item).collect(Collectors.toList()); 

更新(サーバーからの読み込み)

単一のプロパティ(abc) - リストタイプ

Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("abc").as("abc")); 
List<String> singleResults = (List<String>) mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getUniqueMappedResult().get("abc"); 

複数のプロパティ(pqrxyz) - 地図タイプ

何を示唆して反復集計結果のより多くのスタイルの方法(この方法は、従来使用して反復するよりも効率的であるなら、私が知っているのである
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz")); 
Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult(); 
+0

ため、各ループ)。私はMongoDBサーバーで実際の処理が行われる解決策を探していました。 – Harish

+0

さて、あなたのコメントに基づいて回答を更新しました。お気軽に批判してください。 – Veeram

関連する問題