如何检查字符串是否在 pymongo.collection.collection 对象中

How to check if string is in pymongo.collection.collection object

我正在寻找解决此问题的方法,但找不到任何实用的方法

假设我们有一个 pymongo collection 字符串,我们正在其中搜索名为 "tk_dd_id" 的字符串。

collection =   Collection(Database(MongoClient(host=['123234'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='mongomongo'), 'health_cards'), 'tk_dd_id')

我试过了

if "tk_dd_id" in collection:
        print("Found!")

'Collection' object is not iterable

类型(集合)

if any("tk_dd_id" in s for s in collection):
        print("Found!")

'Collection' object is not iterable

type(collection)
<class 'pymongo.collection.Collection'>

这个问题似乎没有实际意义,因为您必须将集合名称作为参数传递给 Collection 对象。但是如果你必须查询名称,你可以使用 name 属性来完成:

from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

collection_name = "tk_dd_id"
collection = Collection(Database(MongoClient(host=['123234'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='mongomongo'), 'health_cards'), collection_name)

if "tk_dd_id" in collection_name:
    print("Found!")

if "tk_dd_id" in collection.name:
    print("Found!")