2017-05-05 5 views
0

私はオーダーコレクションを持っており、orderLastStatusChangeDatetime、estimatedDeliveryDatetimeおよびorderPriceはオーダーコレクションの名前です。 orderPriceの合計を取得する必要があります。ここで、orderLastStatusChangeDatetimeはestimatedDeliveryDatetime以下です。以下のクエリを使用して合計レコードを取得しました。spring mongodb集計2つのフィールドを比較して1つの列の合計を得る

Criteria criteria = new Criteria() { 
     @Override 
     public DBObject getCriteriaObject() { 
      DBObject obj = new BasicDBObject(); 
      obj.put("$where", "this.orderLastStatusChangeDatetime <= this.estimatedDeliveryDatetime"); 
      return obj; 
     } 
    }; 

    Query query = new Query(); 


    query.addCriteria(criteria); 


    totalOrder = (int) mongoTemplate.count(query,ORDERS_COLLECTION_NAME); 

しかし、私は注文価格の合計を取得する必要があります。私は集計マッチで同じ基準を使用しています。しかし、エラーが発生する "コマンドはエラー16395で失敗しました: '例外:$は$一致集計式の内部では使用できません'"

答えて

1

以下のアグリゲーションパイプラインを使用できます。 $sumtrueに等しいcmp$group$matchorder price続いorderLastStatusChangeDatetime <= estimatedDeliveryDatetimeための結果を保持する$project段階でcmpフィールドを作成します。

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

Aggregation aggregation = newAggregation(project("orderPrice").andExpression("orderLastStatusChangeDatetime <= estimatedDeliveryDatetime").as("cmp"), match(Criteria.where("cmp").is(true)), group().sum("orderPrice").as("total")); 

BasicDBObject results = mongoOperations.aggregate(aggregation, ORDERS_COLLECTION_NAME, BasicDBObject.class).getUniqueMappedResult(); 
int totalOrder = results.getInt("total"); 

更新:あなたのクイックヘルプVeeramに使用AggregationExpression 1.8.5でRELEASE

Aggregation agg = newAggregation(
    project("orderPrice").and(new AggregationExpression() { 
       @Override 
       public DBObject toDbObject(AggregationOperationContext context) { 
        return new BasicDBObject("$lte", Arrays.<Object>asList("$orderLastStatusChangeDatetime", "$estimatedDeliveryDatetime")); 
        } 
    }).as("cmp"), 
    match(Criteria.where("cmp").is(true)), 
    group().sum("orderPrice").as("total") 
); 
+0

おかげで...しかし、私はエラーが--- – Pankaj

+0

java.lang.IllegalArgumentExceptionが取得しています:サポートされていない要素:ORG .springframework.data.mongodb.core.spel.OperatorNode @ 542dba3fタイプ:class org.springframework.data.mongodb.core.spel.OperatorNodeおそらくSpEL式に構文エラーがあります。 – Pankaj

+0

ようこそ。私はこれを1.10.1 spring mongoバージョンでうまく実行することができました。あなたは私にコードを表示することができますし、あなたはどのバージョンを使用していますか?これはサーバー '{" $ project ":{" orderPrice ":1、" cmp ":{" $ lte ":[" $ orderLastStatusChangeDatetime "、" $ estimatedDeliveryDatetime "]}}}、{クエリ – Veeram

関連する問題