【问题标题】:Group by month and year when date in string format in MongoDB在MongoDB中以字符串格式的日期按月和年分组
【发布时间】:2019-07-30 01:13:11
【问题描述】:

我收藏的日期是字符串格式。我正在尝试按月和年对值进行分组。我试过$toDate$dateFromString。当我尝试$month$year 时,我得到了一些1 的月份和年份的随机年份。

我不知道接下来我应该做什么。如何按月和年分组?

这是我的代码:

db.hb_data.aggregate([{
$match: {
    date: {$exists: true}
}
}, {
    $group: {
        _id: {date: "$date"},
        video_starts:{$sum: '$video_starts'}
    }
}, {
    $project: {
        month: { $month: new Date("$_id.date") } ,
        year: { year: new Date("$_id.date") } ,
        date: "$_id.date",
        video_starts: '$video_starts'
}   }
])

这是我的结果:

My result

当我的日期为字符串格式时,如何按月和年获取总和?

【问题讨论】:

    标签: mongodb date group-by aggregate pymongo


    【解决方案1】:

    假设这是数据集。

    [
      {"Id_Cust": "4145","firstName": "Albade","lastName": "Maazou", "gender": "female","date": "21/03/1981"},
      {"Id_Cust": "5296", "firstName": "Rafael","lastName": "Oliveira","gender": "male","date": "08/06/1987"},
      {"Id_Cust": "6192","firstName": "Abdul Rahman","lastName": "Budjana","gender": "male","date": "26/01/1990"}
    ]
    

    您可以通过以下方式使用$dateFromString

    db.collection.aggregate([
      {
        $project: {
          month: {
            $month: {
              $dateFromString: {
                dateString: "$date",
                format: "%d/%m/%Y"
              }
            }
          },
          year: {
            $year: {
              $dateFromString: {
                dateString: "$date",
                format: "%d/%m/%Y"
              }
            }
          }
        }
      },
    
    ])
    

    输出:

    [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "month": 3,
        "year": 1981
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "month": 6,
        "year": 1987
      },
      {
        "_id": ObjectId("5a934e000102030405000002"),
        "month": 1,
        "year": 1990
      }
    ]
    

    更新

    您也可以使用$toDate 来执行此操作,但您的字符串日期格式应为"yyyy-mm-dd" 格式,例如{$toDate: "2018-03-03"}

    db.collection.aggregate([
      {
        $project: {
          month: {
            $month: {
              $toDate: "$date"
            }
          },
          year: {
            $year: {
              $toDate: "$date"
            }
          }
        }
      }
    ])
    

    它提供与上面完全相同的输出但请确保您的字符串日期为"yyyy-mm-dd"这种格式。

    【讨论】:

    • 我收到"Unrecognized expression '$dateFromString'" 错误。
    • 你用的是哪个版本的mongo?
    • 我使用的是 3.4.9
    • '$dateFromString' 仅从 3.6 开始受支持。
    • 检查更新部分你也可以使用$toDate
    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2012-02-03
    相关资源
    最近更新 更多