【问题标题】:Interpret 'collection' in db.collection.drop() as variable vs. set database将 db.collection.drop() 中的“集合”解释为变量与设置数据库
【发布时间】:2018-04-10 12:09:18
【问题描述】:

我正在尝试遍历 MongoDB 3.4 数据库中的集合列表并执行更新和删除。我试图让代码将“集合”解释为字符串变量,但代码认为它是一个单一的数据库:

for collection in db.collection_names():
    if collection[-3:] == "_CS":
        request = [UpdateMany({},{"$set": {"Collection": collection}})]
        result = db.collection.bulk_write(request)

    else:
        db.collection.drop() 

有没有另一种方法可以通过 Python/Pymongo 删除一个集合,该方法将集合的名称作为参数,或者有没有一种方法可以解析“集合”以便解释器意识到它是一个变量?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    在循环块中,collection 名称绑定到 str 对象。

    字典样式索引在此处可用于访问具有collection 名称的集合。 例如

    for collection in db.collection_names():
        if collection[-3:] == "_CS":
            request = [UpdateMany({},{"$set": {"Collection": collection}})]
            result = db[collection].bulk_write(request)
    
        else:
            db[collection].drop()
    

    或者,使用pymongo.database.Database 实例的get_collection 方法。

    for collection in db.collection_names():
        if collection[-3:] == "_CS":
            request = [UpdateMany({},{"$set": {"Collection": collection}})]
            result = db.get_collection(collection).bulk_write(request)
    
        else:
            db.get_collection(collection).drop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多