Python Can';无法正确打印mongo查询的大小
我目前正在尝试打印mongo查询的内容,方法是将其强制转换为列表,然后尝试访问该列表的长度,我使用以下代码:Python Can';无法正确打印mongo查询的大小,python,mongodb,list,pymongo,Python,Mongodb,List,Pymongo,我目前正在尝试打印mongo查询的内容,方法是将其强制转换为列表,然后尝试访问该列表的长度,我使用以下代码: from pymongo import MongoClient from elasticsearch import Elasticsearch from datetime import datetime from dateutil.parser import parse from pprint import pprint client = MongoClient('...') db_
from pymongo import MongoClient
from elasticsearch import Elasticsearch
from datetime import datetime
from dateutil.parser import parse
from pprint import pprint
client = MongoClient('...')
db_profile = client['...-profiles']
collection_profile = db_profile['profiles']
# print(collection_profile.count())
querydate = datetime(2020, 1, 1)
year = querydate.year
month = querydate.month
yesterday = querydate.day
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = parse(dateStr)
result = collection_profile.find({'createdAt': {'$gte': date}})
pprint(list(result)) # Here I got the data correctly
print(len(list(result))) # Here I got 0 as result
如果我切换最后两行的位置,我得到了正确的大小,但随后是一个空列表。
有什么不对劲吗?使用
pymongo
访问查询内容是否有更好的方法?因为find函数是一个迭代器,所以只能遍历一次。在第一次pprint(list(result))
之后,result
迭代器到达查询的末尾。从那时起,它将不再返回任何数据
您需要将第一次列表转换存储在变量中,以便再次访问内容:
resultList = list(result)
pprint(resultList) # will use list that is now in memory
print(len(resultList)) # this will work
如果结果集非常大,则可能会导致内存溢出或性能下降。Mongo可以使用集合的count()函数返回计数,您可以将相同的查询对象传递给该函数。因为find函数是一个迭代器,所以只能执行一次。在第一次
pprint(list(result))
之后,result
迭代器到达查询的末尾。从那时起,它将不再返回任何数据
您需要将第一次列表转换存储在变量中,以便再次访问内容:
resultList = list(result)
pprint(resultList) # will use list that is now in memory
print(len(resultList)) # this will work
如果结果集非常大,则可能会导致内存溢出或性能下降。Mongo可以使用集合的count()函数返回计数,您可以将相同的查询对象传递给该函数