gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:02:09 25 4
gpt4 key购买 nike

我是用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}

关于python - 如何将 pymongo.cursor.Cursor 转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28968660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com