0

I want to execute the following mongodb query:

db.clicks.aggregate([
  { $project: { mongoTimestamp: { $add: [new Date(0), "$createdAt"] } } },
  {
    $project: {
      month_clicked: { $month: "$mongoTimestamp" },
      year_clicked: { $year: "$mongoTimestamp" }
    }
  },
  {
    $group: {
      _id: { year_clicked: "$year_clicked", month_clicked: "$month_clicked" },
      clickCount: { $sum: 1 }
    }
  }
]);

However I can't seem to figure out how to pass "new Date(0)" as mongo expression from Spring Rest code. I have tried the following code :

AggregationExpression sumExp = new AggregationExpression() {

    @Override
    public org.bson.Document toDocument(AggregationOperationContext context) {
        BasicDBObject bdbo = new BasicDBObject();
        bdbo.append("$add", Arrays.<Object> asList("new Date(0)", "$createdAt"));
        return new org.bson.Document("mongoTimestamp", bdbo);
    }
};

But the new Date(0) portion is sent over as string "new Date(0)" vs plain new Date(0)

I am using Mongo 3.2.5 and can't upgrade to Mongo 4.

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
  • Try `bdbo.append("$add", Arrays. asList(new Date(0), "$createdAt"));`. Import java.util.Date – s7vr Nov 22 '19 at 23:43
  • 1
    Do you need to use `Date`? That class is poorly designed and long outdated. I suggest you check whether for example you may use `Instant` from java.time, the modern Java date and time API. – Ole V.V. Nov 24 '19 at 16:40

1 Answers1

0

You can use the new Date() object of java.util.Date and passed it in the query as follows.

   import java.util.Date;
   import java.util.Calendar;

   AggregationExpression sumExp = new AggregationExpression() {

        @Override
        public org.bson.Document toDocument(AggregationOperationContext context) {
            Date date = new Date(0);
            BasicDBObject bdbo = new BasicDBObject();
            bdbo.append("$add", Arrays.<Object> asList(date, "$createdAt"));
            return new org.bson.Document("mongoTimestamp", bdbo);
        }
    };

For more details, please check the link on the github: https://github.com/deftlabs/mongodb-examples/blob/master/mongo-java-date-test/src/main/com/deftlabs/tests/mongo/DateTest.java

Or on another stackoverflow question: Java/MongoDB query by date

krishna Prasad
  • 3,541
  • 1
  • 34
  • 44
  • I tried using java.util.Date object but that didn't work. The projection portion of query with new java.util.Date(0) object: { "$project" : { "createdAt" : 1, "mongoTimestamp" : { "$add" : [{ "$date" : 0 }, "$createdAt"] } } }. I need to invoke new Date(0) as mongodb function to convert timestamp in milliseconds to ISO date – Imran Khan Nov 24 '19 at 06:58
  • @ImranKhan have you checked the Github repo codes and another question suggested, I think that will solve your problem. – krishna Prasad Nov 27 '19 at 02:19