PyMongo按多个关键点分组 [英] PyMongo group by multiple keys

查看:0
本文介绍了PyMongo按多个关键点分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PyMongo时,似乎可以按一个键分组:

results = collection.group(key={"scan_status":0}, condition={'date': {'$gte': startdate}}, initial={"count": 0}, reduce=reducer)

结果:

{u'count': 215339.0, u'scan_status': u'PENDING'} {u'count': 617263.0, u'scan_status': u'DONE'}

但当我尝试按多个键分组时,出现异常:

results = collection.group(key={"scan_status":0,"date":0}, condition={'date': {'$gte': startdate}}, initial={"count": 0}, reduce=reducer)

如何才能正确地按多个字段分组?

推荐答案

如果您尝试计算两个以上的密钥,则虽然可以使用.group(),但更好的选择是通过.aggregate()

这使用"本机代码操作符",而不是.group()所要求的JavaScript解释代码来执行与您试图实现的相同的基本"分组"操作。

这里特别是$group管道运算符:

result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": "$date"
        },
        "count": { "$sum": 1 }
    }}
])

实际上,您可能需要将"日期"缩短为不同的时间段。如:

result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": {
                "year": { "$year": "$date" },
                "month": { "$month" "$date" },
                "day": { "$dayOfMonth": "$date" }
            }
        },
        "count": { "$sum": 1 }
    }}
])

使用Date Aggregation Operators,如下所示。

或者使用基本的"日期数学":

import datetime
from datetime import date

result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    # use "epoch" "1970-01-01" as a base to convert to integer
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": {
                "$subtract": [
                    { "$subtract": [ "$date", date.fromtimestamp(0) ] },
                    { "$mod": [
                        { "$subtract": [ "$date", date.fromtimestamp(0) ] },
                        1000 * 60 * 60 * 24
                    ]}
                ]
            }
        },
        "count": { "$sum": 1 }
    }}
])

它将返回来自"纪元"时间的整数值,而不是必需值对象。

但所有这些选项都比.group()好,因为它们使用本机编码的例程,并且执行操作的速度比您在其他情况下需要提供的Java代码快得多。

这篇关于PyMongo按多个关键点分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆