用$set指定一个键的值,如果不存在,就创建它。这对更新模式或者增加用户定义很有帮助。
db.user.insert({"name":"codingwhy.com"})
此用户现在只有姓名信息,现在需要给他添加email
db.user.update({"name":"codingwhy.com"},{"$set":{"email":"example@example.com"}}) { "_id" : ObjectId("55092691591555a6c35dd698"), "name" : "codingwhy.com", "email" : "example@example.com" }
比如现在他又要添加他的个人爱好,他可能有很多的爱好,所以爱好应该是一个数组
db.user.update({"name":"codingwhy.com"},{"$set":{"hobby":["swimming","running","reading"]}}) { "_id" : ObjectId("55082691591555a6c35dd698"), "name" : "codingwhy.com", "email" : "example@example.com", "hobby" : [ "swimming", "running", "reading" ] }
假如他现在又没有爱好了...
db.user.update({"name":"codingwhy.com"},{"$unset":{"hobby":1}}) { "_id" : ObjectId("55082691591555a6c35dd698"), "name" : "codingwhy.com", "email" : "example@example.com" }爱好就没了...