发电机功能与pymongo

时间:2011-07-20 06:34:52

标签: python mongodb generator pymongo

我正在尝试制作一个生成器函数,在每次调用时产生一个项目,但是我不断获得相同的项目。这是我的代码:

  1 from pymongo import Connection
  2 
  3 connection = Connection()
  4 db = connection.store
  5 collection = db.products
  6 
  7 def test():
  8         global collection #using a global variable just for the test.
  9         items = collection.find()
  10        for item in items:
  11                 yield item['description']
  12        return

1 个答案:

答案 0 :(得分:1)

首先,删除return,这不是必需的。

您的问题不在于test(),而在于您如何调用它。不要只是致电test()

做类似的事情:

for item in test():
    print item

你一次可以获得一件物品。这样做基本上是:

from exceptions import StopIteration
it = iter(test())

while True:
    try:
        item = it.next()
    except StopIteration:
        break
    print item