【问题标题】:Pymongo can not perform aggregating with pipeline in too large collectionPymongo 无法在太大的集合中使用管道执行聚合
【发布时间】:2015-04-14 16:16:49
【问题描述】:

我在patients colletion 中有数十亿条记录, 我不知道如何用管道过滤它。

或者这是对 mongoDB 的限制,我们无法在大型集合上与管道聚合?

我已经添加了allowDiskUse=True 选项,但它也不起作用。

如何获得管道过滤后的结果?

我怎样才能简单地将过滤后的结果存储到另一个集合中?谢谢

示例代码(我使用pymongo,所以以下是Python语法)

import datetime
pipeline = [
        {"$project": {"birthday":1, "id":1}
    },
    {
             "$match": { "birthday":{"$gte":datetime.datetime(1987, 1, 1, 0, 0)} }    
     },{"$group": ~~~
     }
    ]
res =db.patients.aggregate(pipeline,allowDiskUse=True)

异常信息

OperationFailure: command SON([('aggregate', u'patients'), ('pipeline', [{'$match': {'birthday': {'$gte': datetime.datetime(1987, 1, 1, 0, 0)}}}]), ('allowDiskUse', True)]) on namespace tw_insurance_security_development.$cmd failed: exception: aggregation result exceeds maximum document size (16MB)    

如何

【问题讨论】:

  • 看起来您在聚合返回游标之前使用的是 MongoDB 版本。升级到 >= 2.6。

标签: mongodb pymongo


【解决方案1】:

将您的结果存储在collection 中,然后对其进行另一次聚合传递。这是mongo的限制,您可以阅读更多关于它的信息here

【讨论】:

  • 我怎样才能简单地将过滤后的结果存储到另一个集合中?谢谢
  • 作为聚合管道的最后一步,添加一个out 运算符。
【解决方案2】:

如果这是针对具有基于人的 UI 的应用程序,那么我建议使用分页 - 通过 mongo 的跳过和限制,并将字段限制为所述人可以查看的字段(您似乎正在使用 $项目)。

“我不知道如何用管道过滤它。” 试试下面的

i_Limit = 100 # Or whatever value plays nice
cnt_Skip = 0
has_Next = True

while has_Next:

         pipe = [{"$project": {"birthday":1, "id":1}},{"$match": { "birthday":{"$gte":datetime.datetime(1987, 1, 1, 0, 0)}}}, {$skip: cnt_Skip},{$limit: i_Limit}, {"$group": ~~~ }]   

        cursor =db.patients.aggregate(pipe,allowDiskUse=True)

        if not cursor:
            has_Next = False
            continue

        for record in cursor:

            # Do whatever needed with the record
            print record



        cnt_Skip = cnt_Skip + i_Limit

如果要进行大转储,请使用mongoexport

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2021-12-06
    • 2017-05-28
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多