更新Mongodb的collection记录,不保留新记录上没有的字段



是否有一种方法在Mongodb中更新记录和删除不存在于更新版本的字段?

与现有记录类似:

{
   "id": "helloworld",
   "icon": "globe",
   "title": "Hello World!",
}

当用这个更新时,它看起来像没有更新,因为它没有删除"图标"。

{
   "id": "helloworld",
   "title": "Hello World!",
}

我能想到的唯一选择是删除记录并再次插入它,或者找出不存在的字段并使用$unset。

我只是想知道是否有更好的方法来做我想要的Mongodb

如果更新文档只包含字段:值对(而不是使用$set等更新操作符),则更新方法也可以完全替换文档

例如

> db.world.insert( {
   "id": "helloworld",
   "icon": "globe",
   "title": "Hello World!",
  } )
> db.world.update( 
     { id: "helloworld" }, 
     { "id": "helloworld", title: "Hello World!" }
)
> db.world.find()
{ "_id" : ObjectId("5320e93b80b181227adb0e24"), 
   "id" : "helloworld",
   "title" : "Hello World!"
}

另一个例子,你也可以看到

http://docs.mongodb.org/manual/reference/method/db.collection.update/example-update-replace-fields

希望能有所帮助

最新更新