2017-05-04 6 views
0
db.test.aggregate(
    [ { 
     $group: 
     { 
      _id: "$id", 
      "total":{$sum: 1}, 
      "live" : { $sum : {$cond : { if: { $eq: ["$status",A"]},then: 1, else: 0}}}, 
      "chat_hrs" :{ $avg: { $subtract: [ "$end_time", "$start_time" ] } }}}]). 

上記のクエリにmongodb集約を使用するようにspringmvcコーディングを書いてください。スプリングデータを使用してグループ内で合計と条件を使用する方法mongodb集約

+0

あなたがこれまでにポストにしようとしたものを追加してください。ここではいくつかの例であるhttp://docs.spring.io/spring-data/data-mongo/docs/current/reference/html/#mongo.aggregation – Veeram

+0

I試み、次のコード、集約集約= newAggregation( \t \t \t \tプロジェクト "(id"、 "$ id") \t \t .andExpression( "終了時間 - 開始時間")as( "AvgTime") \t \t .andExpression( "Status"、 "A")as( "lives") 、 \t \t \t \t \tグループ( "$番号")。(カウント)。( "合計") \t \tとして210 .addToSet( "ID")。( "ID") \t \t \t .avg( "AvgTime")など。( "chat_hrs") \t \t \t .addToSet( "命")など。( "ライブ" など)); – madhu

+0

あなたの春の質問は質問に投稿されたあなたのmongoの質問とは異なります。実際のクエリを私に見せてもらえますか? – Veeram

答えて

1

以下の集計パイプラインを使用することができます。生成された

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; 
import static org.springframework.data.mongodb.core.aggregation.ArithmeticOperators.*; 
import static org.springframework.data.mongodb.core.aggregation.ConditionalOperators.when; 
import static org.springframework.data.mongodb.core.query.Criteria.where; 

Aggregation aggregation = 
      newAggregation(
       project("id"). 
        and(when(where("status").is("A")).then(1).otherwise(0)).as("status"). 
        and(Subtract.valueOf("end_time").subtract("start_time")).as("diffTime"), 
       group("$id").count().as("total").sum("status").as("live").avg("diffTime").as("chat_hrs")); 

モンゴ問合せ:

[{ 
    "$project": { 
     "id": 1, 
     "status": { 
      "$cond": { 
       "if": { 
        "$eq": ["$status", "A"] 
       }, 
       "then": 1, 
       "else": 0 
      } 
     }, 
     "diffTime": { 
      "$subtract": ["$end_time", "$start_time"] 
     } 
    } 
}, { 
    "$group": { 
     "_id": "$id", 
     "total": { 
      "$sum": 1 
     }, 
     "live": { 
      "$sum": "$status" 
     }, 
     "chat_hrs": { 
      "$avg": "$diffTime" 
     } 
    } 
}] 
関連する問題