如何在MongoDB中更新嵌套字段且不丢失原有数据?
解决MongoDB子文档更新不覆盖原有数据的问题
Hey there! I totally get where you're stuck—your current update is replacing the entire keys subdocument because you're passing a new object directly to $set for that field. Instead, we need to target the specific new field inside keys without touching the existing data.
Correct Update Command
Use dot notation to specify the new subfield you want to add, and MongoDB will preserve the rest of the keys content:
db.collection_name.update( {"_id": 1}, {$set: {"keys.updatedTes": "string"}} )
Why This Works
- The filter
{"_id": 1}still correctly targets your document. - By writing
{"keys.updatedTes": "string"}, you're telling MongoDB to only add (or update, if it already exists) theupdatedTesfield within thekeyssubdocument. Your originallogin_idandtransaction_keyvalues will stay right where they are.
Bonus: Add Multiple Fields at Once
If you ever need to add or update several fields in keys later, you can extend the $set like this—no overwriting happens here either:
db.collection_name.update( {"_id": 1}, {$set: { "keys.updatedTes": "string", "keys.another_field": "new_value" }} )
内容的提问来源于stack exchange,提问作者catter
相关产品推荐
相关产品推荐

