You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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) the updatedTes field within the keys subdocument. Your original login_id and transaction_key values 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:24:51