将输入类型从字符串更改为数据,MONGO DB

Change type of input from string to data, MONGO DB

我正在尝试将数据库中每个对象的 inspection_date 字段从 string 转换为 date。 每个对象都是这样构建的。

  "name": " 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//]}

如何转换所有 inspection_date 字段,避免自己一个一个地转换?

根据 @turivishal 的建议,您必须使用 $map$dateFromString 运算符。

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