【问题标题】:Overwriting a field with new data用新数据覆盖字段
【发布时间】:2020-05-12 16:46:11
【问题描述】:

我正在尝试将 createddate 和 endDate 从字符串类型覆盖为日期类型。

我有将它从字符串更改为日期的代码(在此回答 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" } }
                ]
              }
            }
          ]
        }
      }
    }
  }}
])

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

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

谢谢

【问题讨论】:

    标签: mongodb mongodb-query aggregate-functions


    【解决方案1】:

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

    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" }
      ])
    

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

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 2019-12-22
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多