简体   繁体   English

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

[英]How to convert a pymongo.cursor.Cursor into a dict?

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).我正在使用 pymongo 查询一个区域内的所有项目(实际上是查询地图上一个区域内的所有场地)。 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 results which contains the venues.我之前使用db.command(SON())在球形区域中进行搜索,它可以返回一个字典,并且在字典中有一个名为results的键,其中包含了场地。 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.Cursor class and I have no idea how to extract the venue results from it.现在我需要在一个正方形区域中进行搜索,建议我使用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 的值,使用这些值但它不会从这些代码中打印任何内容

The find method returns a Cursor instance, 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 .要获取与给定条件匹配的第一个文档,您需要使用find_one The result of find_one is a dictionary. find_one的结果是一个字典。

You can always use the list constructor 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}

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你去吧

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 方式操作它。

The MongoDB find method does not return a single result, but a list of results in the form of a Cursor . MongoDB find方法不返回单个结果,而是以Cursor的形式返回结果列表。 This latter is an iterator, so you can go through it with a for loop.后者是一个迭代器,因此您可以使用for循环遍历它。

For your case, just use the findOne method instead of find .对于您的情况,只需使用findOne方法而不是find This will returns you a single document as a dictionary.这将返回一个作为字典的文档。

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM