MongoDB根据其他标签的值在嵌套标签中更新

时间:2019-07-17 15:05:16

标签: mongodb

我需要根据其他标签的值重新插入内部标签。

在更新数据之前:

{
    "_id" : "12345",
    "empid" : "12345",
    "dept" : "csc",
    "contacts" : [ 
        {
            "contact_id" : "1",
            "contact" : [ 
                {
                    "address_line1" : "111",
                    "address_line2" : "112"
                }, 
                {
                    "address_line3" : "121",
                    "address_line4" : "122"
                }
            ]
        }, 
        {
            "contact_id" : "2",
            "contact" : [ 
                {
                    "address_line1" : "211",
                    "address_line2" : "212"
                }, 
                {
                    "address_line3" : "221",
                    "address_line4" : "222"
                }
            ]
        }
   ]
}

在上述empid = 12345标签中的contact_id = 2contacts数据(基于此标签值,需要更新)中,address_line3的数据应为已更新。

更新数据后,应在下面查看。

{
    "_id" : "12345",
    "empid" : "12345",
    "dept" : "csc",
    "contacts" : [ 
        {
            "contact_id" : "1",
            "contact" : [ 
                {
                    "address_line1" : "111",
                    "address_line2" : "112"
                }, 
                {
                    "address_line3" : "121",
                    "address_line4" : "122"
                }
            ]
        }, 
        {
            "contact_id" : "2",
            "contact" : [ 
                {
                    "address_line1" : "211",
                    "address_line2" : "212"
                }, 
                {
                    "address_line3" : "updated_data",    # here is the update
                    "address_line4" : "updated_data"     # here is the update
                }
            ]
        }
   ]
}

如果address_line3address_line4标签本身不存在,则应创建标签。

我在python中尝试过的操作

    filter = {"_id":"12345",
              "empid": "12345",
              "contacts.contact_id": "2"
              }

    new_data = {"address_line3": "updated_data","address_line4": "updated_data"}

    mycollection.update(
        filter,
        {"$set": {"contacts.$.contact": new_data }},
        upsert=True
    )

但是,我遇到了错误

pymongo.errors.WriteError: The positional operator did not find the match needed from the query.

请提出可能是问题所在。

0 个答案:

没有答案