MongoDB—— 寫操作 Core MongoDB Operations (CRUD)


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( <document> )
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( <query>,
                      <update>,
                      { upsert: true } )

如果沒有文檔符合查詢要求<query>,則插入文檔,舉例如下:
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( <query>, <update>, <options>
使用方法同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

Name Description
$inc Increments the value of the field by the specified amount.
$rename Renames a field.
$setOnInsert Sets the value of a field upon documentation creation during an upsert. Has no effect on update operations that modify existing documents.
$set Sets the value of a field in an existing document.
$unset Removes the specified field from an existing document.

Array Operators

Name Description
$ Acts as a placeholder to update the first element that matches the query condition in an update.
$addToSet Adds elements to an existing array only if they do not already exist in the set.
$pop Removes the first or last item of an array.
$pullAll Removes multiple values from an array.
$pull Removes items from an array that match a query statement.
$pushAll Deprecated. Adds several items to an array.
$push Adds an item to an array.

Modifiers

Name Description
$each Modifies the $push and$addToSet operators to append multiple items for array updates.
$slice Modifies the $push operator to limit the size of updated arrays.
$sort Modifies the $push operator to reorder documents stored in an array.

Bitwise

Name Description
$bit Performs bitwise AND andOR updates of integer values.

Isolation

Name Description
$isolated Modifies behavior of multi-updates to improve the isolation of the operation.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章