简体   繁体   English

使用PyMongo重命名嵌入式文档中的字段

[英]Rename field in embedded document with PyMongo

I have a collection in mongodb and I want to rename some fields name. 我在mongodb中有一个集合,我想重命名一些字段名称。 My collection is like: 我的收藏如下:

    {
    "_id": "",
    "user": "5a02d87ac12d314721bd9a15",
    "item": {
        "5b20db50a32c0e02693ffad6": {
            "item_value": [{
                "timepstamp": "",
                "value": 0.2
            }, {
                "timepstamp": "",
                "value": 0.8
            }, {
                "timepstamp": "",
                "value": 0.9
            }]
        },
        "843ujsafu88gfs88987898f": {
            "item_value": [{
                "timepstamp": "",
                "value": 0.2
            }, {
                "timepstamp": "",
                "value": 0.8
            }, {
                "timepstamp": "",
                "value": 0.9
            }]
        }
    }
}

I want to rename the "5b20db50a32c0e02693ffad6" and "843ujsafu88gfs88987898f" which are the keys after the item with new values i have lets say "12345x" and "12345y" 我想重命名"5b20db50a32c0e02693ffad6""843ujsafu88gfs88987898f" ,它们是具有新值的项目之后的键,我要说"12345x""12345y"

How can I perform that query in pymongo? 如何在pymongo中执行该查询? I can retrieve the value from the collection with the following code: 我可以使用以下代码从集合中检索值:

db = client['db']
collection = db['col']
res = collection.find({})

for item in res:
    items= item["item"]
    for key in items:
         print (key)
    ## collection.update({}, {$rename: {item["item"][key]: item["item"][new_item_id]}}, False, True)

That code return the keys that I want to rename. 该代码返回我要重命名的密钥。 How can I do so? 我该怎么办?

EDIT: I tried to use the collection update and the method rename. 编辑:我试图使用集合更新和方法重命名。 It seems that it does not work. 似乎不起作用。 How can I change that field only and how I will use properly pymongo here? 我如何只更改该字段,以及如何在此处正确使用pymongo?

EDIT2: In my case I need to do something like that: EDIT2:就我而言,我需要做这样的事情:

 _id = res['_id']
 item.pop('_id')   # this is imp
 _user = item['user']
 item.pop('user')   # this is imp

 collection.update({'_id': _id, 'user': _user }, {$set: item})

To rename field in MongoDB, we usually use the $rename update operate which works beautifully with embedded document as well. 要重命名MongoDB中的字段,我们通常使用$rename更新操作,该操作也可以很好地与嵌入式文档一起使用。

from pymongo import MongoClient


uri = mongodb://127.0.0.1:27017"

old_fields_names = ["5b20db50a32c0e02693ffad6",
                    "843ujsafu88gfs88987898f"]
new_fields_names = ["12345x", "12345y"]
with MongoClient(uri) as client:
    db = client.db
    col = db.col
    update_doc = {f"item.{old}": f"item.{new}"
                  for old, new in zip(old_fields_names, new_field_names)}
    update = {"$rename": update_doc}
    col.update_many({}, update)

Note the use of the context manager aka with statement to open the connection to the database, which ensure the connection is close when we are done with the operation to avoid leaking resources. 请注意,使用上下文管理器(又称为with语句)来打开与数据库的连接,这可以确保在完成操作后关闭连接,以避免资源泄漏。

I think you have already come to right steps only few more steps remaining. 我认为您已经走了正确的一步,仅剩几步了。 Below will work. 下面将工作。 Also, I am assuming that you already have a mapping which key you want to replace and to what - 另外,我假设您已经有了要替换的键以及要替换的键的映射-

db = client['db']
collection = db['col']
res = collection.find({})

for doc in res:
    items= doc["item"]
    for key in items:
         # Now suppose you want to replace this key 
        if key want to replace:
             temp = copy.deepcopy(items[key])
             items["new_Key_name"] = temp
             items.pop(key)  # deleting old key with data

     # Now one document has been modified with expected key Now update the DB
     _id = copy.deepcopy(doc['_id'])
     doc.pop('_id')   # this is imp
     collection.update({'_id': _id }, {$set: doc})

Now One Suggestion in the End. 现在最后一个建议。 Do not use above approach because there are DB Queries inside Loop which is not good. 不要使用上述方法,因为Loop内有DB查询是不好的。 Learn about BulkWrite given in Pymongo Documentation. 了解Pymongo文档中提供的BulkWrite。 Its very easy. 这很容易。

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

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