用新数据覆盖字段

时间:2020-01-27 10:08:47

标签: mongodb mongodb-query aggregate-functions

我正试图将createdstring和endDate从字符串类型覆盖为日期类型。

enter image description here

我有代码将其从字符串更改为日期(在此处Convert Date to String in nested array in mongodb回答)

Cases.aggregate([
  { "$addFields": {
    "cases": {
      "$map": {
        "input": "$cases",
        "in": {
          "$mergeObjects": [
            "$$this",
            {
              "createddate": {
                "$cond": [
                  { "$eq": ["$$this.createddate", " "] },
                  null
                  { "$dateFromString": { "dateString": "$$this.createddate" } }
                ]
              },
              "endDate": {
                "$cond": [
                  { "$eq": ["$$this.endDate", " "] },
                  null
                  { "$dateFromString": { "dateString": "$$this.endDate" } }
                ]
              }
            }
          ]
        }
      }
    }
  }}
])

一旦运行,它将日期显示为日期对象,但是一旦刷新文档,日期将再次返回到字符串。

如何保存它,以便保存(覆盖)值。

谢谢

1 个答案:

答案 0 :(得分:0)

万一其他人想这样做,我已经找到了答案。

db.cases.aggregate([
    { $match: { companyID: 218 }},
    { "$addFields": {
      "cases": { "$map": { "input": "$cases", "in": { "$mergeObjects": [ "$$this", {
        "createddate": {
          "$cond": [
            { "$eq": ["$$this.createddate", " "] },
            null,
            { "$dateFromString": { "dateString": "$$this.createddate" } }
          ]
        },
        "endDate": {
          "$cond": [
            { "$eq": ["$$this.endDate", " "] },
            null,
            { "$dateFromString": { "dateString": "$$this.endDate" } }
          ]
        }}]}}}
    }},
    { "$out": "cases" }
  ])

感谢问题Store location data in Mongodb document的@assh