user1350889
user1350889

Reputation: 93

Using MongoDB dateToString with timezone in project aggregation from spring boot

I want to created following MongoDB aggregation pipeline from Java Spring Boot

  "pipeline": [
    {
      "$project": {
        productType: 1,
        created: 1,
        date: {
          $dateToString: {
            timezone: "Europe/Zurich",
            format: "%Y.%m.%d",
            date: "$created"
          }
        }
      }
    }
  ]

This code is working and creates the pipeline - unfortunately without the timezone part:

  Aggregation agg = newAggregation(
          project("productType", "created")
                  .andExpression("created").dateAsFormattedString("%Y.%m.%d").as("date")
  );

How to adapt the Java Code so that $dateToString uses timezone and the result looks like this:

_id: "def166b4-967d-45ae-8b1c-1f05f8a1fc20"
productType: "car"
created: 2019-04-13T23:23:42.617+00:00
date: "2019.04.14"

Upvotes: 0

Views: 589

Answers (1)

artiomi
artiomi

Reputation: 625

Try using and method which accepts a custom expression instead of andExpression

     Aggregation.newAggregation(
        Aggregation.project("productType", "created")
            .and(DateOperators.zonedDateOf("created", Timezone.valueOf("Europe/Zurich")).toString("%Y.%m.%d"))
    );

Upvotes: 1

Related Questions