2017-08-27 12 views
1

のは、私がコレクションitemsを持っており、これらは、このコレクション内のデータで言ってみましょう:JavaモデルでMongoDBの春データ集計平均

{ 
    "_id": 1 
    "tags": ["handbag", "women", "leather"] 
    "price": 30 
}, { 
    "_id": 2 
    "tags": ["jewelry", "women", "necklace"] 
    "price": 40 
}, { 
    "_id": 3 
    "tags": ["men", "leather", "necklace"] 
    "price": 10 
} 

Iの平均価格を取得するにはどうすればよい

class Item { 
    public ObjectId id; 
    public List<String> tags; 
    public int price; 
} 

leatherとタグ付けされているアイテムはありますか?

私はMongoDBのCLIから私はこれを得ることができることを知っている:

db.items.aggregate([ 
    { $match: { tags: { $in: ["leather"] } } }, 
    { $group: { _id: null, averagePrice: { $avg: "$price" } } } 
]) 

しかし、どのように私はJavaの春ブーツ/データコードにこれを変換することができますか? Aggregation.group()メソッドはフィールドの名前のみを受け入れます。_id: nullを指定することはできません。そのため、一致するすべての要素を1つのグループとしてグループ化します。ここで

は、Java

Javaで
Aggregation.newAggregation(
    match(Criteria.where("tags").in("leather")), 
    group("_id") // how to group all matching rows in one group. 
       .avg("price").as("averagePrice") 
); 
+0

文書のためのあなたの同等のJavaモデルは何か? – nullpointer

+0

質問をモデルに更新しました。 – danial

+1

'' Aggregation agg = Aggregation.newAggregation( )( "leather")) group().avg( "price")as( "averagePrice") ) ; ' – Veeram

答えて

0

で集計クエリで、関連するコードは、多少のようにする必要があります:

collection.aggregate(
    Arrays.asList(
     Aggregates.match(Filters.eq("tags", "leather")), 
      Aggregates.group("$price", Accumulators.avg("$price", "averagePrice")) 
    ) 
) 
+0

同じ価格の要素を一度しか数えないようにするには、値段でグループ化しますか? – danial