I am using MongoDB as a database, and today I encountered a problem when trying to update multiple embedded documents of a document at the same time.
Use Environment: Python3.6 PyMongo Driver
Table format before update:
{
"_id" : 0,
"sys" : {
"group" : 0,
"status" : 1,
"regtime" : NumberLong(1527240646218)
},
"info" : {
"name": "Gui Xiaofang"
}
}
Updated data already generated:
{
'sys': {
'group': 0,
'status': 2
},
'info': {
Name',' Gui Xiaofang',
'mail': 'abc@abc.com',
'phone': '+1234567'
}
}
I need to get updated tables:
{
"_id" : 0,
"sys" : {
"group" : 0,
"status": 2, // Update here
"regtime" : NumberLong(1527240646218)
},
"info" : {
"name": "Gui Xiaofang",
Mail': 'abc@abc.com', // Update here
Phone': '+1234567' // Update here
}
}
But when I try to use it$set
The updater updates the document in the following statement:
database.users.update(
{"_id": uid},
{"$set": data} // data here refers to the above updated data
)
However, the results are as follows:
{
"_id" : 0,
"sys" : {
"group" : 0,
"status": 2 // The regtime key I need to keep disappears
},
"info" : {
"name": "Gui Xiaofang",
Mail': 'abc@abc.com', // The update was successful here
Phone': '+1234567' // updated successfully here
}
}
After searching on Google, I understood the cause of the problem: use$set
The updater will replace the value of the key specified in the document, but the embedded document will also be completely replaced by the new document. If the value of the embedded document needs to be partially updated, it needs to be doneinfo.$
Such updates.
However, my table does not have a fixed pattern, and update data is also generated, so I would like to ask you if you have any direct method to update multiple embedded documents at the same time. Thank you!
Your understanding may be wrong.
info.$
It is an update to the matched array elements and has nothing to do with embedded documents.
I don’t know what’s above youdata
What exactly is the specific content? Judging from the results, it should be:data = { "sys" : { "group" : 0, "status" : 2 }, "info" : { "name": "Gui Xiaofang", Mail': 'abc@abc.com', // Update here Phone': '+1234567' // Update here } }
It is possible to get your results. If
data
This is indeed the value, then this result is no problem. To get the result you want, the correct update statement should be:db.users.update({ "_id": uid }, { 'sys.status': data.sys.status, 'info': data.info });