如果要操作数组中的值,可以用值在数组中的位置当做参数来删除
db.user.update({"name":"codingwhy.com"},{"$set":{"hobby.0":"crying"}}){ "_id" : ObjectId("55082691591555a6c35dd698"), "name" : "codingwhy.com", "email" : "example@example.com", "hobby" : [ "crying", "running", "reading", "sleeping", "singing", "eating", "dancing" ] }
现在哭成了主要爱好了,这不行,咱得改了,但是如果不事先去查,我们并不知道哭是这个hobby数组的第几个值,MongoDB为我们考虑到了这点,使用$来代替位置。
db.user.update({"hobby":"crying"},{"$set":{"hobby.$":"smiling"}}){ "_id" : ObjectId("55082691591555a6c35dd698"), "name" : "codingwhy.com", "email" : "example@example.com", "hobby" : [ "smiling", "running", "reading", "sleeping", "singing", "eating", "dancing" ] }