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

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

有人知道我是否应该将光标转换成一个结果并提取出来,或使用另一种方法来查询项目在一个正方形区域? 顺便说一句,db 是 pymongo.Database. Database 类

密码是:

>>> 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 的值,使用这些值,但它不会从这些代码中输出任何内容

165778 次浏览

The MongoDB find method 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 for loop.

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

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

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

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

The find method returns a Cursor instance, which allows you to iterate over all matching documents.

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

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.

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


Demo using 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:

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

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.

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

Map function is fast way to convert big collection

from time import time




cursor = db.collection.find()


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


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