【问题标题】:Extract month and year from mongodb Datetime filed and Group_by in Django从 Django 中的 mongodb Datetime 字段和 Group By 中提取月份和年份
【发布时间】:2019-12-02 16:27:36
【问题描述】:

我在我的 Django 项目中使用 monogengine,我想要 count() 每年和每个月的工作数量。 每次用户完成一些工作后,它都会很好地插入并保存在我的数据库中。现在我想对它们进行计数,并稍后在一些图表中以年月格式使用这个数字。

这是我的模特

from mongoengine import Document, EmbeddedDocument, fields

class PortModel(EmbeddedDocument):
    idx=fields.StringField()
    protocolname=fields.StringField()
    protocolnumber=fields.StringField()
    description=fields.StringField(required=False, blank=True)

class PortScanModel(Document):
    date=fields.DateTimeField()
    host=fields.StringField()
    ip=fields.StringField()
    Ports=fields.ListField(fields.EmbeddedDocumentField(PortModel))

我想要像 group_by 这样的东西,只是在年和月上计算行数并提取有多少用户使用它。 我的日期字段类似于“2019-12-02T19:47:31.847170”,我想要如下所示:

year-month | number of rows
---------------------------
2018-01    | 2
2018-02    | 7
2019-01    | 3
2019-05    | 14

我搜索了很多从日期中提取年份和月份的内容,但没有找到。 我不知道我是否可以在一个命令中提取和分组在 mongo 中,但在 SQL 中并不难。

感谢您的帮助。

【问题讨论】:

  • 你试过ExtractMonth DB功能吗?
  • @JPG annotate 不能在 django 中使用 monoengine,但感谢您的回复

标签: python django mongodb date group-by


【解决方案1】:

经过长时间的搜索,我找到了答案,我想与他人分享。 在我的情况下,我应该使用 aggregate() 从 dateTime 字段中提取年份和月份,然后对它们进行分组link

$month --> extract month from date
$year  --> extract year from date
$group --> group_by command
$sum   --> for counting something (here +1)

所以,我改变了我的查询如下:

    pipeline = [
    {
        "$group":{
            "_id":{
                "year": {"$year": "$date"},
                "month":{"$month":"$date"}
                },
                "total": { "$sum": 1 }
                }
    }]

我的python查询是这样的:

PortScanModel.objects.aggregate(*pipeline)

完成!此命令首先从 date 中提取年和月,然后按 group_by 年和月提取行数。现在我有他们每年每月的计数,我可以绘制使用图表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2023-03-17
    • 2019-06-04
    • 2021-10-02
    • 2018-02-16
    相关资源
    最近更新 更多