Search code examples
mongodbaggregation-frameworkbson

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?


Solution

  • Use $toDate instead of $dateFromString.

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

    BsonDocument

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

    Sample Mongo Playground