user1765862
user1765862

Reputation: 14145

MongoDB - Conditionally check value for null in the pipeline

In my MongoDB doc, I have updated field of type string

In the pipeline, I'm consuming that field ...

{
   ...
   "$dayOfMonth", new BsonDocument(){
      {"$dateFromString", new BsonDocument(){{"dateString", "$updated"}}
    }
    ...
}

Everything seems to be in order if I have values in the collection document but if pipeline steps into the document with no value I'm getting

Command aggregate failed: $dateFromString requires that 'dateString' be a string, found: date with value 2022-02-23T01:54:21.467Z.

How can I conditionally check in the pipeline for the value of this property?

Upvotes: 0

Views: 145

Answers (1)

Yong Shun
Yong Shun

Reputation: 51240

Use $toDate instead of $dateFromString.

{
  $dayOfMonth: {
    $toDate: "$updated"
  }
}

BsonDocument

{
   "$dayOfMonth", new BsonDocument() {
      { "$toDate", "$updated" }
   }
}

Sample Mongo Playground

Upvotes: 1

Related Questions