{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"url": "http://www.baidu.com",
"count": 2 }
Run: db.accessLog.update({“url”:”http://www.baidu.com“},{“$inc”: {“count”,1}});
注意:$inc仅适用于整数,长整数,双精度浮点数;
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "hank",
"age": 20,
"sex": male }
Run: db.user.update({“name”:”hank”},{“$set”:{“book”:”green eggs and ham”}});
Run:*db.user.update({“name”:”hank”},{“$unset”:{“age”: 1}});
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "elvis blog",
"content": "......" }
Run: db.blog.update({“name”:”elvis blog”},{“$push”:{“comments”:{“name”:”hank”,”email”:”hank@163.com”,”phone”:”13825647428”}}})
执行之后可查数据格式:
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "elvis blog",
"content": "......",
"comment":[ { "name":"hank", "email":"hank@163.com", "phone":"13825647428" } ] }
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "elvis blog",
"content": "......",
"comment":[ { "name":"hank", "email":"hank@163.com", "phone":"13825647428" } , { "name":"even", "email":"even@163.com", "phone":"13825647428" } ] }
*Run:db.blog.update({“name”:{“$ne”:”hank”}},{“$push”:{“type”:”News”}};
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "elvis blog",
"content": "......",
"emails":[ "zhangsan@163.com" ] }
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"name": "elvis blog",
"content": "......",
"emails":[ "zhangsan@163.com" ] }
*Run:db.blog.update({“_id”: ObjectId(“565f8fc5e4b0719ee3bd7cb5”)},
{“$addToSet”:{“emails”:{“$each:{“wangwu@163.com”,”zhaoliu@outlook.com”
,chengqi@gamail.com}}});
$pop按位置删除元素
$pull按条件删除元素
若是数组有多个值,我们只想对其中一部分进行操作,那此时我们有两种方法可以实现,可以通过位置,也可以通过定位操作符(“$”)
{
"_id": ObjectId("565f8fc5e4b0719ee3bd7cb5"),
"content": "......",
"comments":[ { "content":"goos post" "votes": 1 }, { "content":"too short" "votes": 2 }, { "content":"free watches" "votes": 3 } ] }
此时,如果我们想增加某个comments的votes的话,那么我们可以通过数组元素下标来update
Run:db.collection.update({“_id”: ObjectId(“565f8fc5e4b0719ee3bd7cb5”)},{“$inc”:{“comments.0.votes”:4}})
但是,在绝大多数情况下,我们并不知道将要修改的元素的下标是多少,那么在这种情况下,就可以使用定位操作符来修改了
Run:db.collection.update({“comments.content”:”free watches”},{“comments.$.votes”:10})
情景【accessLog】:假设一个集合放的是一个网站相关的用户数据(如下),每次有用户访问该网站时即给其访问次数加1,如果能找到特定url,那就给访问次数加1,否则就新建一个文档.在这种情况下,我们欲更改用户访问量,那么或许就要打个来回,如果多个用户访问同一个网站时,我们还要考虑某些限制,那么这种情况下不妨考虑Upsert命令,作用一样,但更高效
Run:db.blog.update({“url”:”/elvis.blog”},{“$inc”:{“visits”:1}},true) update的第三个参数就是upert的开启选项(补充一点,update的第四个选项是更新所有比配元素的开启选项,一般,update只会更新匹配到的第一个元素,开启此选项后,将更新所有匹配元素)