MongoDB汇总变化以匹配天差匹配

时间:2018-12-23 00:38:47

标签: java mongodb spring-data-mongodb spring-mongodb

要获得结果或项的天数之差=(一个数字)且$ acceptedDate大于$ liveDate-x天

,此聚合的变化形式是什么?
    AggregationOperation redact = new AggregationOperation() {
        @Override
        public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("if",  BasicDBObject.parse("{'$gte':[{'$subtract':[{'$ifNull':['$acceptedDate', 
{'$date':" + System.currentTimeMillis() + "}]},'$lastVisit' **here minus x days **]},1296000000]}}")); //and the difference is 10 days
        map.put("then", "$$KEEP");
        map.put("else", "$$PRUNE");
        return new BasicDBObject("$redact", new BasicDBObject("$cond", map));
    };

    Aggregation aggregation = Aggregation.newAggregation(redact);

    List<FactoryAcceptance> results = mongoTemplate.aggregate(aggregation, FactoryAcceptance.class, FactoryAcceptance.class).getMappedResults();

基本上是为此目的传递一个参数作为变体,他们希望以天为单位匹配差异(例如,向我显示差异为5天的记录),但在这种情况下,lastVisit应该为负5天。

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询。

BasicDBObject.parse("
  {'$eq':[
     {'$subtract':[
       {'$ifNull':['$acceptedDate',{'$date':" + System.currentTimeMillis() + "}]},
       {'$subtract':['$lastVisit', 216000000]} // 5 days
     ]}, 
     432000000 // 10 days
  ]}"
);