简单的脚本不打印

时间:2016-10-29 07:48:27

标签: python pymongo

我正在尝试对一个集合进行排序,然后打印前5个文档以确保它有效:

#!/user/bin/env python

import pymongo

# Establish a connection to the mongo database.
connection = pymongo.MongoClient('mongodb://localhost')

# Get a handle to the students database.
db = connection.school
students = db.students


def order_homework():

    projection = {'scores': {'$elemMatch': {'type': 'homework'}}}
    cursor = students.find({}, projection)

    # Sort each item's scores.
    for each in cursor:
        each['scores'].sort()

    # Sort by _id.
    cursor = sorted(cursor, key=lambda x: x['_id'])

    # Print the first five items.
    count = 0
    for each in cursor:
        print(each)
        count += 1
        if count == 5:
            break


if __name__ == '__main__':
    order_homework()

当我运行时,没有任何内容打印 如果我拿出各种各样的,那就打印出来 每种单独运行时都可以使用。

请告诉我我做错了什么/教育我。

1 个答案:

答案 0 :(得分:2)

您尝试将光标视为列表,您可以从一开始就多次迭代。 PyMongo游标不会这样做 - 一旦你在for each in cursor中迭代它,光标就会完成,你不能再次迭代它。

您可以将光标变为如下列表:

data = list(students.find({}, projection))

为了提高效率,请从MongoDB中预先排序结果:

list(students.find({}, projection).sort('_id'))

这会将排序标准发送给服务器,然后服务器会将结果流式传输回您预先排序,而不是要求您在客户端执行此操作。现在删除你的"按_id排序"下面的一行。

相关问题