Mongo 聚合:使用 new Date() 作为输入以形成 AggregationExpression

Mongo Aggregation: Using new Date() as in input to form a AggregationExpression

有谁知道如何用 spring mongo 投影实现这个语句:

timed: {
   $divide: [{ $subtract: [ new Date(), "$created" ] }, 7200000]
}

像这样的东西对我不起作用:

ArithmeticOperators.Subtract updated = valueOf("new Date()").subtract("created");

因为 valueOf 需要字段引用或 AggregationExpression

你可以在舞台下面试试。 shell 查询中的 new Date() 是 javascript 日期函数。您必须使用 BasicDBObject 将该表达式包装在 AggregationExpression 中。

 ArithmeticOperators.Divide updated = ArithmeticOperators.Divide.valueOf(aggregationOperationContext -> new BasicDBObject("$subtract", Arrays.asList(new Date(), "$created"))).divideBy(7200000);
 AggregationOperation project = Aggregation.project().and(updated).as("timed");
 Aggregation agg = newAggregation(project);

我无法找到一种方法来传递类似两个日期参数的东西

valueOf("created").subtract(new Date())

我遇到了和你一样的问题。我通过以下代码修复它:

    String pattern = "yyyy-MM-dd HH:mm:ss";
    String dateNow = DateFormatUtil.getDateNow();
    DateOperators.DateFromString date = DateOperators.dateFromString(dateNow);
    date.withFormat(pattern);
    ArithmeticOperators.Subtract subtract = ArithmeticOperators.Subtract.valueOf("deadline").subtract(date);
    ArithmeticOperators.Divide divide = ArithmeticOperators.Divide.valueOf(subtract).divideBy(3600000);

subtract() 方法可能需要一个类似 AggregationExpression 的参数,而 DateOperators.dateFromString 是实现。 我希望这会有所帮助。 0-0