从3.6开始,你必须使用new运算符$expr
,它允许在匹配查询或常规查询中使用聚合表达式.
您可以创建json查询并直接传递它,因为$expr
Spring在常规查询中不支持.
15天= 15*24*60*60*1000 = 1296000000毫安
Query query = new BasicQuery("{'$expr':{'$gte':[{'$subtract':[{'$ifNull':['$acceptedDate',{'$date':" + System.currentTimeMillis() + "}]},'$lastVisit']},1296000000]}}"); Listresults = mongoTemplate.find(query, Document.class);
3.4版本
如果你想使用spring mongo方法,你必须使用投影来添加保持比较的新字段,然后是匹配操作和额外投影以删除比较字段.不幸的$addFields
是仍然不支持,所以你必须使用AggregationOperation
手动创建一个新的阶段.
AggregationOperation addFields = new AggregationOperation() { @Override public Document toDocument(AggregationOperationContext aggregationOperationContext) { Document document = new Document("comp", Document.parse("{'$gte':[{'$subtract':[{'$ifNull':['$acceptedDate', {'$date':" + System.currentTimeMillis() + "}]},'$lastVisit']},1296000000]}}")); return new Document("$addFields", document); } }; Aggregation aggregation = Aggregation.newAggregation( addFields, Aggregation.match(Criteria.where("comp").is(true)) Aggregation.project().andExclude("comp"); ); Listresults = mongoTemplate.aggregate(aggregation, collection name, Document.class).getMappedResults();
3.2版本
AggregationOperation redact = new AggregationOperation() { @Override public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) { Mapmap = new LinkedHashMap<>(); map.put("if", BasicDBObject.parse("{'$gte':[{'$subtract':[{'$ifNull':['$acceptedDate', {'$date':" + System.currentTimeMillis() + "}]},'$lastVisit']},1296000000]}}")); map.put("then", "$$KEEP"); map.put("else", "$$PRUNE"); return new BasicDBObject("$redact", new BasicDBObject("$cond", map)); }; Aggregation aggregation = Aggregation.newAggregation(redact); List results = mongoTemplate.aggregate(aggregation, FactoryAcceptance.class, FactoryAcceptance.class).getMappedResults();