使用 Pymongo 删除字段

Deleting Field using Pymongo

我没有足够的声誉来发表评论,因此我不得不再次提出这个问题。

我尝试了不同的方法来删除此处提到的动态更改的日期列,但对我没有任何作用:How to remove a field completely from a MongoDB document?

Environment_Details - OS:Windows10,pymongo:3.10.1,MongoDB 指南针应用:4.4,python:3.6

我正在尝试删除“2020/08/24”列(在我的情况下,这个日期是动态的)。我的数据如下所示:

    [{
  "_id": {
    "$oid": "5f4e4dda1031d5b55a3adc70"
  },
  "Site": "ABCD",
  "2020/08/24": "1",
  "2020/08/25": "1.0"
},{
  "_id": {
    "$oid": "5f4e4dda1031d5b55a3adc71"
  },
  "Site": "EFGH",
  "2020/08/24": "1",
  "2020/08/25": "0.0"
}]

不会给我任何错误但也不会删除 column/field“2020/08/24”的命令:

col_name = "2020/08/24"
db.collection.update_many({}, {"$unset": {f"{col_name}":1}})
db.collection.update({}, {"$unset": {f"{col_name}":1}}, False, True)
db.collection.update_many({}, query =[{ '$unset': [col_name] }])

我在尝试将 multi:True 与更新选项一起使用时总是 运行 出错。

我使用的确切代码是:

    import pymongo
def connect_mongo(host, port, db):
    conn = pymongo.MongoClient(host, port)
    return conn[db]


def close_mongo(host, port):
    client = pymongo.MongoClient(host, port)
    client.close()


def delete_mongo_field(db, collection, col_name, host, port):
    """Delete column/field from a collection"""
    db = connect_mongo(host, port, db)
    db.collection.update_many({}, {"$unset": {f"{col_name}":1}})
    #db.collection.update_many({}, {'$unset': {f'{col_name}':''}})
    close_mongo(host,port)      

        
col_to_delete = "2020/08/30"
delete_mongo_field(mydb, mycollection, col_to_delete, 'localhost', 27017)

另外,您可能需要考虑更改数据模型以将日期存储为值而不是键,并考虑将它们存储为本机日期对象,例如

import datetime
import pytz

db.testcollection.insert_many([
    {
        "Site": "ABCD",
        "Dates":  [
            {
                "Date": datetime.datetime(2020, 8, 24, 0, 0, tzinfo=pytz.UTC),
                "Value": "1"
            },
            {
                "Date": datetime.datetime(2020, 8, 25, 0, 0, tzinfo=pytz.UTC),
                "Value": "1.0"
            }]
    },
    {
        "Site": "EFGH",
        "Dates": [
            {
                "Date": datetime.datetime(2020, 8, 24, 0, 0, tzinfo=pytz.UTC),
                "Value": "1"
            },
            {
                "Date": datetime.datetime(2020, 8, 25, 0, 0, tzinfo=pytz.UTC),
                "Value": "0.1"
            }]
    }])

但是回到你的问题……第一个例子对我来说很好用。您能否尝试下面的示例代码,看看是否会得到不同的结果:

from pymongo import MongoClient
import pprint

db = MongoClient()['testdatabase']

db.testcollection.insert_many([{
    "Site": "ABCD",
    "2020/08/24": "1",
    "2020/08/25": "1.0"
}, {
    "Site": "EFGH",
    "2020/08/24": "1",
    "2020/08/25": "0.0"
}])
pprint.pprint(list(db.testcollection.find({}, {'_id': 0})))

col_name = "2020/08/24"
db.testcollection.update_many({}, {"$unset": {f"{col_name}": 1}})

pprint.pprint(list(db.testcollection.find({}, {'_id': 0})))

结果:

[{'2020/08/24': '1', '2020/08/25': '1.0', 'Site': 'ABCD'},
 {'2020/08/24': '1', '2020/08/25': '0.0', 'Site': 'EFGH'}]
[{'2020/08/25': '1.0', 'Site': 'ABCD'}, {'2020/08/25': '0.0', 'Site': 'EFGH'}]

以下代码适用于 Python 3.8、PyMongo 3.11 和 MongoDB v 4.2.8。

col_name = '2020/08/24'
result = collection.update_many( { }, { '$unset': { col_name: '' } } )
print(result.matched_count, result.modified_count)

post 中的两个文档已更新,名称为 "2020/08/24" 的字段已删除。注意:MongoDB 集合的文档可以有一个带有 / 字符的字段名称(参见 Documents - Field Names)。


[编辑添加]

以下 delete_mongo_field 函数对我有用,通过删除提供的字段名称来正确更新文档:

def delete_mongo_field(db, collection, col_name, host, port):
    db = connect_mongo(host, port, db)
    result = db[collection].update_many( { }, { '$unset': { col_name: 1 } } ) # you can also use '' instead of 1
    print(result.modified_count)