MongoDB:db.collection.find() 返回的对象为 pymongo.cursor.Cursor而不是dict或list

    技术2023-05-04  87

    目录

    MongolDB查询模拟

    输出结果

     将返回的结果在内存中转化为list

    当pymongo.cursor.Cursor没有抓到数据时,就无法判断next(),即会报错

    粗略看一下这个数据包装类的可迭代实现 

     


     


    MongolDB查询模拟

    import pymongo x = db.col.find() # 直接打印输出内容,发现继承的是object,而不是dict或者list print(x) # 识别试下他的类型 print(type(x)) # 判断一下是否是可迭代对象 print(hasattr(x, '__iter__')) print(hasattr(x, '__next__')) # 是否实现了__dict__ print(hasattr(x, '__dict__')) # 输出插入的所有文档对应的 _id 值 print(f'{collection} col find count: {len(x)}')

    输出结果

    <pymongo.cursor.Cursor object at 0x00000147062B0C88> <class 'pymongo.cursor.Cursor'> True True True Traceback (most recent call last): File "E:/work_space/warclouds/version01/openstack_api_server/cloudenforce/vmware_api/vcenter_mongo.py", line 98, in <module> find_object(collection='vcenter_vm') File "E:/work_space/warclouds/version01/openstack_api_server/cloudenforce/vmware_api/vcenter_mongo.py", line 92, in find_object print(f'{collection} col find count: {len(x)}') TypeError: object of type 'Cursor' has no len()

     将返回的结果在内存中转化为list

    # 判断一下是否是可迭代对象 print(hasattr(x, '__iter__')) print(hasattr(x, '__next__')) # print(hasattr(x, '__dict__')) # 将可迭代对象转化为list result = [doc for doc in x] print(result) # 输出插入的所有文档对应的 _id 值 print(f'{collection} col find count: {len(result)}')

    当pymongo.cursor.Cursor没有抓到数据时,就无法判断next(),即会报错

    <pymongo.cursor.Cursor object at 0x0000021A8E5AEC50> <class 'pymongo.cursor.Cursor'> Traceback (most recent call last): File "E:/work_space/warclouds/version01/openstack_api_server/cloudenforce/vmware_api/vcenter_mongo.py", line 101, in <module> find_object(collection='vcenter_vm') File "E:/work_space/warclouds/version01/openstack_api_server/cloudenforce/vmware_api/vcenter_mongo.py", line 85, in find_object print(x.next()) File "E:\work_space\warclouds\version01\openstack_api_server\venv\lib\site-packages\pymongo\cursor.py", line 1164, in next raise StopIteration StopIteration

    粗略看一下这个数据包装类的可迭代实现 

    class CousorType: ..... def __iter__(self): return self def next(self): """Advance the cursor.""" if self.__empty: raise StopIteration if len(self.__data) or self._refresh(): if self.__manipulate: _db = self.__collection.database return _db._fix_outgoing(self.__data.popleft(), self.__collection) else: return self.__data.popleft() else: raise StopIteration __next__ = next

     

    Processed: 0.011, SQL: 9