python - 如何在 MongoDB python 中获取集合的单个值
问题描述
我在 MongoDB 中有以下 python 代码:
input_1 = object_collection.find({"_id": ObjectId(key_1)})
for i in input_1:
print(i)
它返回这个:
{'_id': ObjectId('5d949843cc1e1fc0556983bc'), 'x_input': '11', 'y_input': '22'}
我只对它们x_input
以及y_input
我想存储它们的位置感兴趣,以便计算它们的相同点
解决方案
因此,您可以在查询中使用“项目”...
from pymongo import MongoClient
from bson import ObjectId
if __name__ == '__main__':
client = MongoClient("localhost:27017", username="barry", password="barry", authSource="admin", authMechanism="SCRAM-SHA-256")
with client.start_session(causal_consistency = True) as my_session:
with my_session.start_transaction():
db = client.mydatabase
collection = db.mycollection
for result in collection.find({"_id": ObjectId("5d97713e11261b4afebe517b")}, {"_id": 0, "x_input": 1}):
print (str(result))
看到一点...
{"_id": 0, "x_input": 1}
...这指示查询引擎关闭“_id”的显示,并打开“x_input”的显示。如果我们完全指定任何“项目”,则必须指定我们想要查看的所有字段。“_id” 是这个策略的怪异,除非关闭,否则将始终显示。
结果:
{u'x_input': u'11'}
推荐阅读
- c# - 设备进入睡眠状态后保持 Unity 程序在后台运行?
- ios - 获取大标题导航栏默认收缩和扩展高度
- node.js - 为使用 `require` 导入的对象分配别名
- assembly - 汇编,将单个字节从寄存器写入内存会覆盖其他字节
- python - 无法从网页中抓取所有公司名称
- reactjs - got Can't resolve 'react/jsx-runtime' error while use try to create the shared component with storybook in react-typescript
- python - How to use web scraping to get visible text on the webpage?
- flutter - 如何根据检测到颤振应用程序中的锁定或关闭屏幕采取行动
- ios - SwiftUI IPhone TextFields spanning greater than screen jumping, standard behaviour?
- c++ - MFC C++ - MDI 选项卡式视图下拉列表菜单消失