stranger-thing
stranger-thing

Reputation: 125

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

does anybody know how to achieve this statement with spring mongo projection:

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

Something like this doesn't work for me:

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

because valueOf expects a field reference or an AggregationExpression

Upvotes: 1

Views: 1022

Answers (2)

吕小布
吕小布

Reputation: 1

I meet the same problem as you . I fix it by the following code:

    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() method may need a param like AggregationExpression , and the DateOperators.dateFromString is the implement. I hope this can be helpful. 0-0

Upvotes: 0

s7vr
s7vr

Reputation: 75964

You can try below stage. new Date() in shell query is javascript date function. You have to use the BasicDBObject to wrap that expression inside the 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);

I was not able to find a way to pass something like two date arguments

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

Upvotes: 1

Related Questions