J.F.
J.F.

Reputation: 15207

How to add onError and onNull to $dateFromString in an aggregation update using MongoTemplate

I'm currently working on a project which use MongoTemplate and I would like to do this simply query:

db.collection.update({
  timestamp: null
},
[
  {
    $set: {
      timestamp: {
        $dateFromString: {
          dateString: "$myvalue",
          format: "%Y-%m-%d",
          onError: "$$NOW",
          onNull: "$$NOW"
        }
      }
    }
  }
],
{
  multi: true
})

But I'm stuck on the validation parts, I can't find the way to add onError and onNull into the query.

Currently my code is:

AggregationUpdate update = AggregationUpdate.update()
                .set("timestamp").toValue(DateOperators.dateFromString("$myvalue")
                        .withFormat("%Y-%m-%d"));

mongoTemplate.updateMulti(
        new Query(Criteria.where("timestamp").is(null)),
        update,
        MyClass.class
);

And this works fine... but I'd like to control the errors using onError and onNull.

Is that possible using MongoTemplate?

DateOperators.dateFromString() has methods withFormat() and withTimezone() but I can't see onError() and onNull(), to match with all options according to docs

Thanks in advance

Upvotes: 0

Views: 312

Answers (1)

Aymeric ROEHR
Aymeric ROEHR

Reputation: 26

I encounter a similar issue recently so I put here the solution I came up with.

I ends up to construct "$dateFromString" by hand, so your would become :

AggregationUpdate update = AggregationUpdate.update()
  .set("timestamp").toValue(new BasicDBObject("$dateFromString", 
    new BasicDBObject("dateString", "$myvalue")
      .append("format", "%Y-%m-%d")
      .append("onError", "$$NOW")
      .append("onNull", "$$NOW")));

Upvotes: 1

Related Questions