首页 > 解决方案 > 如何在 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我想存储它们的位置感兴趣,以便计算它们的相同点

标签: pythonmongodbflask

解决方案


因此,您可以在查询中使用“项目”...

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'}

推荐阅读