Gaelix98
Gaelix98

Reputation: 49

Change type of input from string to data, MONGO DB

i'm trying to convert the inspection_date field from string to date for every object inside my db. Every object is built like this one.

  "name": "$1 STORE",
"address": "5573 ROSEMEAD BLVD",
"city": "TEMPLE CITY",
"zipcode": "91780",
"state": "California",
"violations": [{
    "inspection_date": "2015-09-29",
    "description": "       points  ...   violation_status\n62754       1  ...  OUT OF COMPLIANCE\n62755       1  ...  OUT OF COMPLIANCE\n62756       2  ...  OUT OF COMPLIANCE\n\n[3 rows x 5 columns]",
    "risk": "Risk 3 (Low)"
}, {
    "inspection_date": "2016-08-18",
    "description": "        points  ...   violation_status\n338879       2  ...  OUT OF COMPLIANCE\n\n[1 rows x 5 columns]",
    "risk": "Risk 3 (Low)"

} //could be more than 2 or less then 2 object inside violations array//]}

How can i convert all of the inspection_date field avoiding doing it by myself one by one?

Upvotes: 0

Views: 94

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

As suggested by @turivishal, you have to have to make use of $map and $dateFromString operators.

db.collection.aggregate([
  {
    "$addFields": {
      "violations": {
        "$map": {
          "input": "$violations",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                "inspection_date": {
                  "$dateFromString": {
                    "dateString": "$$this.inspection_date",
                    "format": "%Y-%m-%d",
                    "onError": null,
                    "onNull": null
                  }
                }
              }
            ],
            
          },
          
        }
      }
    }
  },
  
])

Mongo Playground Sample Execution

Upvotes: 2

Related Questions