我有一个订单集合和orderLastStatusChangeDatetime,estimatedDeliveryDatetime和orderPrice都是订单集合的归档名称。我必须获得orderPrice的总和,其中orderLastStatusChangeDatetime小于或等于estimatedDeliveryDatetime。我使用以下查询来获取总记录...
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);
但我必须得到订单价格的总和。我在聚合匹配中使用了相同的标准。但它给出了错误&#34;命令失败,错误16395:&#39;异常:$ where不允许在$ match聚合表达式中&#39;&#34;
答案 0 :(得分:2)
您可以使用以下聚合管道。在cmp
阶段创建$project
字段,以保留orderLastStatusChangeDatetime <= estimatedDeliveryDatetime
的结果,然后$match
,cmp
等于true
和$group
} $sum
order price
。{/ p>
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");
更新:在1.8.5 RELEASE中使用AggregationExpression
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")
);
答案 1 :(得分:0)