Python 如何将 pymongo.cursor.Cursor 转换为 dict?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28968660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:57:14  来源:igfitidea点击:

How to convert a pymongo.cursor.Cursor into a dict?

pythonmongodbdictionarymongodb-querypymongo

提问by gladys0313

I am using pymongo to query for all items in a region (actually it is to query for all venues in a region on a map). I used db.command(SON())before to search in a spherical region, which can return me a dictionary and in the dictionary there is a key called resultswhich contains the venues. Now I need to search in a square area and I am suggested to use db.places.find, however, this returns me a pymongo.cursor.Cursorclass and I have no idea how to extract the venue results from it.

我正在使用 pymongo 查询一个区域内的所有项目(实际上是查询地图上一个区域内的所有场地)。我db.command(SON())以前在一个球形区域中搜索,它可以返回一个字典,在字典中有一个results包含场地的键。现在我需要在一个正方形区域中搜索,我建议使用db.places.find,但是,这会返回一个pymongo.cursor.Cursor类,我不知道如何从中提取场地结果。

Does anyone know whether I should convert the cursor into a dict and extract the results out, or use another method to query for items in a square region? BTW, db is pymongo.database.Database class

有谁知道我是否应该将光标转换为字典并将结果提取出来,或者使用另一种方法来查询方形区域中的项目?顺便说一句,db 是 pymongo.database.Database 类

The codes are:

代码是:

>>> import pymongo
>>> db = pymongo.MongoClient(host).PSRC 
>>> resp = db.places.find({"loc": {"$within": {"$box": [[ll_lng,ll_lat], [ur_lng,ur_lat]]}}})
>>> for doc in resp:
>>>     print(doc)

I have values of ll_lng, ll_lat, ur_lng and ur_lat, use these values but it prints nothing from this codes

我有 ll_lng、ll_lat、ur_lng 和 ur_lat 的值,使用这些值但它不会从这些代码中打印任何内容

采纳答案by styvane

The findmethod returns a Cursorinstance, which allows you to iterate over all matching documents.

find方法返回一个Cursor实例,它允许您遍历所有匹配的文档。

To get the first document that matches the given criteria you need to use find_one. The result of find_oneis a dictionary.

要获取与给定条件匹配的第一个文档,您需要使用find_one. 的结果find_one是一本字典。

You can always use the listconstructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.

您始终可以使用list构造函数返回集合中所有文档的列表,但请记住,这会将所有数据加载到内存中,并且可能不是您想要的。

You should do that if you need to reuse the cursor and have a good reason not to use rewind()

如果您需要重用游标并且有充分的理由不使用,则应该这样做 rewind()



Demo using find:

演示使用find

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()  
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
...     print(doc)  # or do something with the document
... 
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}


Demo using find_one:

演示使用find_one

>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}

回答by Alexandre

The MongoDB findmethod does not return a single result, but a list of results in the form of a Cursor. This latter is an iterator, so you can go through it with a forloop.

MongoDBfind方法不返回单个结果,而是以Cursor. 后者是一个迭代器,所以你可以用一个for循环来遍历它。

For your case, just use the findOnemethod instead of find. This will returns you a single document as a dictionary.

对于您的情况,只需使用该findOne方法而不是find. 这将返回一个作为字典的文档。

回答by Yegor Dia

to_dict()Convert a SON document to a normal Python dictionary instance.

to_dict()将 SON 文档转换为普通的 Python 字典实例。

This is trickier than just dict(...) because it needs to be recursive.

这比 dict(...) 更棘手,因为它需要递归。

http://api.mongodb.org/python/current/api/bson/son.html

http://api.mongodb.org/python/current/api/bson/son.html

回答by Saravanan Subramanian

I suggest create a list and append dictionary into it.

我建议创建一个列表并将字典附加到其中。

x   = []
cur = db.dbname.find()
for i in cur:
    x.append(i)
print(x)

Now x is a list of dictionary, you can manipulate the same in usual python way.

现在 x 是一个字典列表,你可以用通常的 python 方式操作它。

回答by Aminah Nuraini

Easy

简单

import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())

print array

There you go

你去吧

回答by Rafal

Map function is fast way to convert big collection

Map函数是转换大集合的快速方法

from time import time


cursor = db.collection.find()

def f(x):
    return x['name']

t1 = time()
blackset = set(map(f, cursor))
print(time() - t1)