简体   繁体   English

使用 Pymongo 删除字段

[英]Deleting Field using Pymongo

I don't have enough reputation to comment and hence I have to ask this question again.我没有足够的声誉发表评论,因此我不得不再次提出这个问题。

I have tried different ways to delete my dynamically changing date column as mentioned here but nothing worked for me : How to remove a field completely from a MongoDB document?我尝试了不同的方法来删除我在这里提到的动态更改的日期列,但对我没有任何作用: 如何从 MongoDB 文档中完全删除字段?

Environment_Details - OS : Windows10, pymongo : 3.10.1, MongoDB Compass App : 4.4, python: 3.6 Environment_Details - 操作系统:Windows10,pymongo:3.10.1,MongoDB Compass App:4.4,python:3.6

I am trying to delete column "2020/08/24"(this date will be dynamic in my case).我正在尝试删除“2020/08/24”列(在我的情况下,此日期将是动态的)。 My data looks like this:我的数据如下所示:

    [{
  "_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"
}]

Commands which don't throw me any error but also don't delete the column/field "2020/08/24":不会向我抛出任何错误但也不会删除列/字段“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] }])

I am always running into error while trying to use multi:True with update option.尝试将 multi:True 与更新选项一起使用时,我总是遇到错误。

The exact code that I am using is:我使用的确切代码是:

    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)

On a separate note, you might want to consider changing your data model to store the dates as values rather than keys, and also to consider storing them as native date objects, eg另外,您可能需要考虑更改数据模型以将日期存储为值而不是键,并考虑将它们存储为本地日期对象,例如

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"
            }]
    }])

But back to you question ... the first example works fine for me.但是回到你的问题......第一个例子对我来说很好。 Can you try the sample code below and see if you get different results:你可以试试下面的示例代码,看看你是否得到不同的结果:

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

Result:结果:

[{'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'}]

The following code worked with Python 3.8, PyMongo 3.11., and MongoDB v 4.2.8.以下代码适用于 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)

The two documents in the post were updated and the field with the name "2020/08/24" was removed.更新了帖子中的两个文档,并删除了名称为"2020/08/24"的字段。 NOTE: A MongoDB collection's document can have a field name with / character (See Documents - Field Names ).注意:MongoDB 集合的文档可以具有带/字符的字段名称(请参阅文档 - 字段名称)。


[EDIT ADD] [编辑添加]

The following delete_mongo_field function worked for me updating the documents correctly by removing the supplied field name:以下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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM