设为首页 收藏本站
查看: 1013|回复: 0

[经验分享] MongoDB—— 写操作 Core MongoDB Operations (CRUD)

[复制链接]

尚未签到

发表于 2015-7-8 07:35:35 | 显示全部楼层 |阅读模式
  MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略。
主要有三种写操作:
        Create
        Update
        Delete

Create:可以分为两种基本操作——insert和updates with the upsert option
  
Insert()
BSON文件最大为16M;_id通常作为主key
为了测试写操作是否成功,可以调用getLastError函数{ getLastError: 1 }
db.collection.insert(  )
insert方法在第一次调用的时候,自动创建collection。
以下例子中bios为collection名,根据自己情况修改。
例如:
db.bios.insert(
   {
     _id: 1,
     name: { first: 'John', last: 'Backus' },
     birth: new Date('Dec 03, 1924'),
     death: new Date('Mar 17, 2007'),
     contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
     awards: [
               {
                 award: 'W.W. McDowell Award',
                 year: 1967,
                 by: 'IEEE Computer Society'
               },
               {
                 award: 'National Medal of Science',
                 year: 1975,
                 by: 'National Science Foundation'
               },
               {
                 award: 'Turing Award',
                 year: 1977,
                 by: 'ACM'
               },
               {
                 award: 'Draper Prize',
                 year: 1993,
                 by: 'National Academy of Engineering'
               }
             ]
   }
)
如果插入操作没有指定_id,则会自动生成一个唯一的id。
使用中括号,同时插入多个文档。
db.bios.insert(
   [
     {
       _id: 3,
       name: { first: 'Grace', last: 'Hopper' },
       title: 'Rear Admiral',
       birth: new Date('Dec 09, 1906'),
       death: new Date('Jan 01, 1992'),
       contribs: [ 'UNIVAC', 'compiler', 'FLOW-MATIC', 'COBOL' ],
       awards: [
                 {
                   award: 'Computer Sciences Man of the Year',
                   year: 1969,
                   by: 'Data Processing Management Association'
                 },
                 {
                   award: 'Distinguished Fellow',
                   year: 1973,
                   by: ' British Computer Society'
                 },
                 {
                   award: 'W. W. McDowell Award',
                   year: 1976,
                   by: 'IEEE Computer Society'
                 },
                 {
                   award: 'National Medal of Technology',
                   year: 1991,
                   by: 'United States'
                 }
               ]
     },
     {
       _id: 4,
       name: { first: 'Kristen', last: 'Nygaard' },
       birth: new Date('Aug 27, 1926'),
       death: new Date('Aug 10, 2002'),
       contribs: [ 'OOP', 'Simula' ],
       awards: [
                 {
                   award: 'Rosing Prize',
                   year: 1999,
                   by: 'Norwegian Data Association'
                 },
                 {
                   award: 'Turing Award',
                   year: 2001,
                   by: 'ACM'
                 },
                 {
                   award: 'IEEE John von Neumann Medal',
                   year: 2001,
                   by: 'IEEE'
                 }
               ]
     },
     {
       _id: 5,
       name: { first: 'Ole-Johan', last: 'Dahl' },
       birth: new Date('Oct 12, 1931'),
       death: new Date('Jun 29, 2002'),
       contribs: [ 'OOP', 'Simula' ],
       awards: [
                 {
                   award: 'Rosing Prize',
                   year: 1999,
                   by: 'Norwegian Data Association'
                 },
                 {
                   award: 'Turing Award',
                   year: 2001,
                   by: 'ACM'
                 },
                 {
                   award: 'IEEE John von Neumann Medal',
                   year: 2001,
                   by: 'IEEE'
                 }
               ]
     }
   ]
)
调用save()函数,通过查询collection中的_id域,来决定使用insert还是update。
upsert flags 当插入的文档已经存在,需要对原文当进行覆盖的时候使用此标记。
db.collection.update( ,
                      ,
                      { upsert: true } )
如果没有文档符合查询要求,则插入文档,举例如下:
db.bios.update(
   {
     _id: 7,
     name: { first: 'Ken', last: 'Thompson' }
   },
   {
     $set: {
             birth: new Date('Feb 04, 1943'),
             contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ],
             awards: [
                       {
                         award: 'Turing Award',
                         year: 1983,
                         by: 'ACM'
                       },
                       {
                         award: 'IEEE Richard W. Hamming Medal',
                         year: 1990,
                         by: 'IEEE'
                       },
                       {
                         award: 'National Medal of Technology',
                         year: 1998,
                         by: 'United States'
                       },
                       {
                         award: 'Tsutomu Kanai Award',
                         year: 1999,
                         by: 'IEEE'
                       },
                       {
                         award: 'Japan Prize',
                         year: 2011,
                         by: 'The Japan Prize Foundation'
                       }
                     ]
           }
   },
   { upsert: true } //如果文档存在,覆盖
)
Update()
主要包括两种操作,update和save
db.collection.update( , ,
使用方法同insert中介绍。
下面分情况举例:
1、更新文件中的域
db.bios.update(
   { _id: 1 },
   {
     $set: { 'name.middle': 'Warner' },
   }
)
更新子文档name中的middle域为warner
2、添加新的域
db.bios.update(
   { _id: 3 },
   { $set: {
             mbranch: 'Navy',
             'name.aka': 'Amazing Grace'
           }
   }
)
添加mbranch域 和子文档name的aka域
3、移除域
db.bios.update(
   { _id: 3 },
   { $unset: { birth: 1 } }
)
4、更新数组
db.bios.update(
   { _id: 1 },
   { $set: { 'contribs.1': 'ALGOL 58' } }
)
更新contribs数组中第二个元素的值
5、定位,然后更新元素
db.bios.update(
       { _id: 3, 'contribs': 'compiler' },
       { $set: { 'contribs.$': 'A compiler' } }
    )
定位id为3,contribs中存在compiler元素的位置,更新为A compiler
6、向数组添加元素
db.bios.update(
   { _id: 1 },
   {
     $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } }
   }
)
添加一个新的awards域的元素
7、更新多个文档
db.bios.update(
   { 'awards.award': 'Turing' },
   { $set: { turing: true } },
   { multi: true }
)
save()函数可以用以下函数来解释:function save( doc ) {
  if( doc["_id"] ) {
       update( {_id: doc["_id"] }, doc, { upsert: true } );
    }
  else {
       insert(doc);
  }
}
Update Operators 操作符


Fields
NameDescription$incIncrements the value of the field by the specified amount.$renameRenames a field.$setOnInsertSets the value of a field upon documentation creation during an upsert. Has no effect on update operations that modify existing documents.$setSets the value of a field in an existing document.$unsetRemoves the specified field from an existing document.
Array Operators

NameDescription$Acts as a placeholder to update the first element that matches the query condition in an update.$addToSetAdds elements to an existing array only if they do not already exist in the set.$popRemoves the first or last item of an array.$pullAllRemoves multiple values from an array.$pullRemoves items from an array that match a query statement.$pushAllDeprecated. Adds several items to an array.$pushAdds an item to an array.
Modifiers
NameDescription$eachModifies the $push and $addToSet operators to append multiple items for array updates.$sliceModifies the $push operator to limit the size of updated arrays.$sortModifies the $push operator to reorder documents stored in an array.
Bitwise
NameDescription$bitPerforms bitwise AND and OR updates of integer values.Isolation
  NameDescription$isolatedModifies behavior of multi-updates to improve the isolation of the operation.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84235-1-1.html 上篇帖子: 快速搭建MongoDB分布式集群 下篇帖子: mongodb 命令
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表