Variables don't hold value for very long pymongo ipython

时间:2015-10-29 15:47:56

标签: pymongo

Perhaps I should just restart my computer, but it seems my variable are losing their values. A simple aggregation only seems to hold the contents of my database for a short period of time. Note: I'm doing this in an ipython notebook.

MONGODB_URI ='mongodb://username:password@***.mongolab.****/***'
client = MongoClient(MONGODB_URI)
db = client.get_default_database()
collectn = db.collection_name

pipe = [
    {"$unwind":"$predictions"},
    {"$match": {"predictions.t_obj": datetime.datetime(2015, 10, 29, 11, 0)}}
]
should_be_data = collectn.aggregate(pipe)
list(should_be_data)
// returns what we expect, i.e. data

list(should_be_data)
// returns []

Why do the contents of my variable disappear?

1 个答案:

答案 0 :(得分:1)

should_be_data不是列表/数据容器,而是生成器

第一次运行list(should_be_data)时,生成器完全耗尽。这些行消耗了生成器中的元素,并将它们存储在新列表中。

第二次运行list(should_be_data)时,生成器已经用尽,因此不再返回元素。

如果您希望它是一个开头的列表,只需替换

should_be_data = collectn.aggregate(pipe)

should_be_data = list(collectn.aggregate(pipe))