Home  >  Article  >  Database  >  MongoDB数据修改总结

MongoDB数据修改总结

WBOY
WBOYOriginal
2016-06-07 17:32:43938browse

最近在学习MongoDB,数据修改这一部分的内容较多,命令比较繁琐,所以将一些常用的修改命令总结在这篇博客中,方便今后学习的查阅

1.前言

最近在学习MongoDB,数据修改这一部分的内容较多,命令比较繁琐,所以将一些常用的修改命令总结在这篇博客中,方便今后学习的查阅。

2.命令总结

1). insert()

db.collection.insert(x) x就是要更新的对象,只能是单条记录,如:

db.collection.insert({_id:1,name:"test",count:1})

当需要批量插入的时候,可以在shell中使用for循环,如:

for(var i=0;idb.mytest.insert({_id:i,name:"test"+i,count:i})
}

此时如果用find()命令查询插入的数据,结果是这样的:

> db.mytest.find()

{ "_id" : 0, "name" : "test0", "count" : 0 }
{ "_id" : 1, "name" : "test1", "count" : 1 }
{ "_id" : 2, "name" : "test2", "count" : 2 }
{ "_id" : 3, "name" : "test3", "count" : 3 }
{ "_id" : 4, "name" : "test4", "count" : 4 }
{ "_id" : 5, "name" : "test5", "count" : 5 }
{ "_id" : 6, "name" : "test6", "count" : 6 }
{ "_id" : 7, "name" : "test7", "count" : 7 }
{ "_id" : 8, "name" : "test8", "count" : 8 }
{ "_id" : 9, "name" : "test9", "count" : 9 }
{ "_id" : 10, "name" : "test10", "count" : 10 }
{ "_id" : 11, "name" : "test11", "count" : 11 }
{ "_id" : 12, "name" : "test12", "count" : 12 }
{ "_id" : 13, "name" : "test13", "count" : 13 }
{ "_id" : 14, "name" : "test14", "count" : 14 }
{ "_id" : 15, "name" : "test15", "count" : 15 }

 

2). update()

db.collection.update( criteria, objNew, upsert, multi ) 四个参数的说明如下:
criteria: update的查询条件,类似sql update查询内where后面的
objNew: update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert: 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi: mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

几个查询例子如下:

db.mytest.update({count:{$gt:1}},{$set:{name:"ok"}}) 只更新第一条记录

db.mytest.update({count:{$gt:3}},{$set:{name:"ok"}},false,true) 大于3的全部更新了

db.mytest.update({count:{$gt:4}},{$set:{name:"ok123"}},true,false) 只更新了一条

db.mytest.update({count:{$gt:6}},{$set:{name:"ok123"}},true,true) 大于6的全部更新了

 

3). save()

db.collection.save(x) x是要插入的对象,效果与上面的insert命令一样。save与insert的区别是这样的:

在进行插入数据的操作中,,当遇到_id相同的情况下,save完成保存操作,insert则会保存;即_id相同情况下,save相当于更新操作。

 下面是一些MongoDB的更新操作符

更多详情见请继续阅读下一页的精彩内容

MongoDB 的详细介绍:请点这里
MongoDB 的下载地址:请点这里

推荐阅读:

Java实现MongoDB中自增长字段

CentOS编译安装MongoDB

CentOS 编译安装 MongoDB与mongoDB的php扩展

CentOS 6 使用 yum 安装MongoDB及服务器端配置

Ubuntu 13.04下安装MongoDB2.4.3

如何在MongoDB中建立新数据库和集合

MongoDB入门必读(概念与实战并重)

《MongoDB 权威指南》(MongoDB: The Definitive Guide)英文文字版[PDF]

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn