python 的pymongo db.collection.find()出来是个游标,怎么才能转成数据?
PHP中文网
PHP中文网 2017-04-18 09:59:10
0
4
838

find出来直接print是<pymongo.cursor.Cursor object at 0x040DC8D0>

网上看到的都是遍历,如果我想把find出来的结果保存到一个列表就不能保存了,所以请问大神要怎么弄?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
巴扎黑
>>> db.test.find()
<pymongo.cursor.Cursor object at 0x108dabf50>
>>>
>>> list(db.test.find())
[{'_id': ObjectId('5839b12eee86fb71849a0905'), 'name': 'Tom'},
 {'_id': ObjectId('5839b134ee86fb71849a0906'), 'name': 'Jim'}]
左手右手慢动作

Using find in pymongo will get a cursor object. If you want to implement the find operation in the MongoDB shell, for example:

> db.test.find()
{ "_id" : ObjectId("5838531e0f3577fc9178b834"), "name" : "zhangsan" }

You need to use find_one method instead of find method in pymongo:

>>> print db.test.find_one()
{u'_id': ObjectId('5838531e0f3577fc9178b834'), u'name': u'zhangsan'}

>>> print db.test.find()
<pymongo.cursor.Cursor at 0x7f4ac789e450>
>>> result = []
>>> for x in db.test.find():
          result.append(x)
>>> print(result)
>>> [{u'_id': ObjectId('5838531e0f3577fc9178b834'), u'name': u'zhangsan'},...]

In this way, you can get multiple pieces of data.

刘奇

All I know is to traverse the cursor and append to the list one by one. Is there any other way? Ask for guidance from God

洪涛

In fact, it is very simple. The above answers are all traversal, in python

array = list(posts.find())#posts是我的collection
type(array)
#list

Just to add

#list to datafram
import pandas as pd
df = pd.DataFrame(array)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!