Mongoengine聚合返回空游标

2024-09-26 22:55:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我使用匹配的表达式执行聚合查询:

>>> devices = [1,2,3,4,5,6] # devices ID's

>>> c = View.objects.aggregate(
{"$match": {"d": {"$in": devices},"f": {"$ne": 1}}}, 
{"$group":{'_id':"uniqueDocs",'count':{"$sum":1}}}
)

我得到了结果:

^{2}$

但如果执行的查询与表达式不匹配:

>>> now = datetime.utcnow().replace(tzinfo=tz.gettz('UTC'))
>>> current_hour_start = now.replace(minute=0, second=0, microsecond=0)
>> c = View.objects.aggregate(
                {"$match": {"d": {"$in": devices}, "b": {"$gte": current_hour_start}, "f": {"$ne": 1}}},
                {"$group": {'_id': "uniqueDocs", 'count': {"$sum": 1}}})

我得到了空光标:

list(c)
[]

我怎么得到零计数?

作为:

>>> list(c)
[{u'count': 0, u'_id': u'uniqueDocs'}]

更新: 示例数据集和预期结果。在

>>> View.objects()

{ 
_id: ObjectId("578f79b877824688fc0d68ed") }, {
    $set: {
        "d": 1, /* device ID */
        "i": 1899,
        "s": 1,
        "a": 1,
        "m": 0,
        "f": 0,
        "b": ISODate("2016-07-20T08:35:56.066Z"), /* begin time */
        "e": ISODate("2016-07-20T08:35:57.965Z") /* end time */
    }
},

{ 
_id: ObjectId("578f79b877824688fc0d68ee") }, {
    $set: {
        "d": 2,
        "i": 2456,
        "s": 1,
        "a": 1,
        "m": 0,
        "f": 0,
        "b": ISODate("2016-07-20T08:37:26.066Z"),
        "e": ISODate("2016-07-20T08:37:28.965Z")
    }
},

{ 
_id: ObjectId("578f79b877824688fc0d68ef") }, {
    $set: {
        "d": 1000,/* !!! ignore this document (no matched device ID)  */
        "i": 2567,
        "s": 1,
        "a": 1,
        "m": 0,
        "f": 0,
        "b": ISODate("2016-07-20T08:35:56.066Z"),
        "e": ISODate("2016-07-20T08:35:57.965Z")
    }
}

>>> c = View.objects.aggregate(
        {"$match": {"d": {"$in": devices},"f": {"$ne": 1}}}, 
        {"$group":{'_id':"uniqueDocs",'count':{"$sum":1}}}
        ).next()['count']

2

Tags: inviewidobjectsmatchcountgroupaggregate

热门问题