Search code examples
stringmongodbdatetimepymongo

Datetime to string in mongodb where only month and year are in data


suppose this is my Data:-

[
  {"Id_Cust": "4145","firstName": "Albade","lastName": "Maazou", "gender": "female","date": "031981"},
  {"Id_Cust": "5296", "firstName": "Rafael","lastName": "Oliveira","gender": "male","date": "061987"},
  {"Id_Cust": "6192","firstName": "Abdul Rahman","lastName": "Budjana","gender": "male","date": "011990"}
]

I try by $datetostring and $datefromstring I also try format but still got an Error:- But, Nothing happened.

OperationFailure: PlanExecutor error during aggregation :: caused by :: an incomplete date/time string has been found, with elements missing: "031981", full error: {'ok': 0.0, 'errmsg': 'PlanExecutor error during aggregation :: caused by :: an incomplete date/time string has been found, with elements missing: "031981"', 'code': 241, 'codeName': 'ConversionFailure'}

Solution

  • Mongo requires the "date" part to fully exist, this means it expects to get at least a year, a month and a day.

    So you can either pad your string with 01 and provide the format option:

    db.collection.aggregate([
      {
        $addFields: {
          date: {
            "$dateFromString": {
              "dateString": {
                "$concat": [
                  "01",
                  "$date"
                ]
              },
              "format": "%d%m%Y"
            }
          }
        }
      }
    ])
    

    Mongo Playground

    Or use $dateFromParts instead:

    db.collection.aggregate([
      {
        $addFields: {
          date: {
            "$dateFromParts": {
              year: {
                "$toInt": {
                  "$substr": [
                    "$date",
                    2,
                    4
                  ]
                }
              },
              month: {
                $toInt: {
                  $substr: [
                    "$date",
                    0,
                    2
                  ]
                }
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground


    Bonus - This requirement is not stated explicitly in the documentation but can be found in the source code:

    if (s->time->y != TIMELIB_UNSET && s->time->m != TIMELIB_UNSET &&
        s->time->d != TIMELIB_UNSET &&
        !timelib_valid_date( s->time->y, s->time->m, s->time->d)) {
        add_pbf_warning(s, TIMELIB_WARN_INVALID_DATE, "The parsed date was invalid", string, ptr);
    }