如何将 pymongo.cursor.Cursor 转换为字典?

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

我正在使用pymongo查询一个区域中的所有项目(实际上是在地图上查询一个区域中的所有场馆)。我之前使用db.command(SON())在一个球形区域中搜索,它可以return我一个字典,在字典中有一个名为results的键,其中包含场地。现在我需要在一个正方形区域中搜索,建议我使用 db.places.find,但是,这个 return 是 pymongo.cursor.Cursor class 我不知道如何提取场地由此产生。

有谁知道我应该将游标转换为字典并提取结果,还是使用其他方法来查询方形区域中的项目? 顺便说一句,分贝是 pymongo.database.Database class

代码是:

>>> 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)

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

MongoDB find 方法不是 return 单个结果,而是 Cursor 形式的结果列表。后者是一个迭代器,因此您可以使用 for 循环遍历它。

对于您的情况,只需使用 findOne 方法而不是 find。这将 return 将单个文档作为字典提供给您。

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

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

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

find method returns a Cursor 实例,它允许您遍历所有匹配的文档。

要获取符合给定条件的第一个文档,您需要使用 find_onefind_one 的结果是一个字典。

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

如果你需要重用游标并且有充分的理由不使用 rewind()

,你应该这样做

演示使用 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}

演示使用 find_one:

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

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

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

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

简单

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)

好了

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)