mongodb 更新并 $set 覆盖文档

mongodb update and $set overwrites the document

假设我有一个文档;

{
  id: 1,
  name: alex, 
  age: 39,
  surname: felix
  address: [
   { 
     type: "home"
     street: "blabla"
   }
  ]
}

当我将查询写为;

db.collection.update({id: 1 , adress.type: "home"} ,  { $set : {adress: { street: "test"}});

它将文档更改为;

{
  id: 1,
  adress: [
      street: test
  ]
}

但是我只想设置文档的一部分,只想更改街道名称但是此查询会覆盖文档。

如何用 update 编辑 mongodb 中文档的部分内容?

你可以试试这个

db.collection.update( 
  { id: 1, "address.type" : "home" } , 
  {$set : {"address.$.street" : "test"}}
);

阅读来自 Docs

的更多内容

可以使用位置 $ 运算符

更新数组中某个位置的项目
db.collection.update( 
    {id: 1 , adress.type: "home"}, 
    { $set: { "adress.$.street": "test" } }
)

!请注意,这仅在找到一 (1) 个子文档时有效