我是用pymongo来查询一个地区的所有元素(其实是在一张 map 上查询一个地区的所有 field )。我之前使用 db.command(SON())
在球形区域中搜索,它可以返回一个字典,并且在字典中有一个名为 results
的键,其中包含场馆。现在我需要在一个正方形区域中搜索,建议我使用 db.places.find
,但是,这会返回一个 pymongo.cursor.Cursor
类,我有不知道如何从中提取 field 结果。
有谁知道我应该将光标转换为字典并提取结果,还是使用其他方法查询方形区域中的项目? 顺便说一句,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 的值,使用这些值但它不会从这些代码中打印任何内容
最佳答案
find
方法返回 Cursor
实例,它允许您遍历所有匹配的文档。
要获取第一个符合给定条件的文档,您需要使用 find_one
. find_one
的结果是一个字典。
您始终可以使用 list
构造函数返回集合中所有文档的列表,但请记住,这会将所有数据加载到内存中,并且可能不是您想要的。
如果您需要重用光标并且有充分的理由不使用 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}
https://stackoverflow.com/questions/28968660/