发布于 2015-09-14 14:48:43 | 166 次阅读 | 评论: 0 | 来源: 网络整理

Of the four basic database operations (i.e. CRUD), update operations are those that modify existing records or documents in a MongoDB collection. For general information about write operations and the factors that affect their performance, see ; for documentation of other CRUD operations, see the 核心操作(CRUD) page.

Overview

Update operation modifies an existing document or documents in a collection. MongoDB provides the following methods to perform update operations:

注解

Consider the following behaviors of MongoDB’s update operations.

  • When performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk and may reorder the document fields depending on the type of update.

  • As of these driver versions, all write operations will issue a getLastError command to confirm the result of the write operation:

    { getLastError: 1 }
    

    Refer to the documentation on write concern in the document for more information.

Update

The update() method is the primary method used to modify documents in a MongoDB collection. By default, the update() method updates a single document, but by using the multi option, update() can update all documents that match the query criteria in the collection. The update() method can either replace the existing document with the new document or update specific fields in the existing document.

The update() has the following syntax:

db.collection.update( <query>, <update>, <options> )

Corresponding operation in SQL

The update() method corresponds to the UPDATE operation in SQL, and:

  • the <query> argument corresponds to the WHERE statement, and
  • the <update> corresponds to the SET ... statement.

The default behavior of the update() method updates a single document and would correspond to the SQL UPDATE statement with the LIMIT 1. With the multi option, update() method would correspond to the SQL UPDATE statement without the LIMIT clause.

Modify with Update Operators

If the <update> argument contains only update operator expressions such as the $set operator expression, the update() method updates the corresponding fields in the document. To update fields in subdocuments, MongoDB uses dot notation.

Update a Field in a Document

Use $set to update a value of a field.

The following operation queries the bios collection for the first document that has an _id field equal to 1 and sets the value of the field middle, in the subdocument name, to Warner:

db.bios.update(
   { _id: 1 },
   {
     $set: { 'name.middle': 'Warner' },
   }
)

Add a New Field to a Document

If the <update> argument contains fields not currently in the document, the update() method adds the new fields to the document.

The following operation queries the bios collection for the first document that has an _id field equal to 3 and adds to that document a new mbranch field and a new aka field in the subdocument name:

db.bios.update(
   { _id: 3 },
   { $set: {
             mbranch: 'Navy',
             'name.aka': 'Amazing Grace'
           }
   }
)

Remove a Field from a Document

If the <update> argument contains $unset operator, the update() method removes the field from the document.

The following operation queries the bios collection for the first document that has an _id field equal to 3 and removes the birth field from the document:

db.bios.update(
   { _id: 3 },
   { $unset: { birth: 1 } }
)

Update Arrays

Update an Element by Specifying Its Position

If the update operation requires an update of an element in an array field, the update() method can perform the update using the position of the element and dot notation. Arrays in MongoDB are zero-based.

The following operation queries the bios collection for the first document with _id field equal to 1 and updates the second element in the contribs array:

db.bios.update(
   { _id: 1 },
   { $set: { 'contribs.1': 'ALGOL 58' } }
)
Update an Element without Specifying Its Position

The update() method can perform the update using the $ positional operator if the position is not known. The array field must appear in the query argument in order to determine which array element to update.

The following operation queries the bios collection for the first document where the _id field equals 3 and the contribs array contains an element equal to compiler. If found, the update() method updates the first matching element in the array to A compiler in the document:

db.bios.update(
       { _id: 3, 'contribs': 'compiler' },
       { $set: { 'contribs.$': 'A compiler' } }
    )
Update a Document Element without Specifying Its Position

The update() method can perform the update of an array that contains subdocuments by using the positional operator (i.e. $) and the dot notation.

The following operation queries the bios collection for the first document where the _id field equals 6 and the awards array contains a subdocument element with the by field equal to ACM. If found, the update() method updates the by field in the first matching subdocument:

db.bios.update(
   { _id: 6, 'awards.by': 'ACM'  } ,
   { $set: { 'awards.$.by': 'Association for Computing Machinery' } }
)
Add an Element to an Array

The following operation queries the bios collection for the first document that has an _id field equal to 1 and adds a new element to the awards field:

db.bios.update(
   { _id: 1 },
   {
     $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } }
   }
)

Update Multiple Documents

If the <options> argument contains the multi option set to true or 1, the update() method updates all documents that match the query.

The following operation queries the bios collection for all documents where the awards field contains a subdocument element with the award field equal to Turing and sets the turing field to true in the matching documents:

db.bios.update(
   { 'awards.award': 'Turing' },
   { $set: { turing: true } },
   { multi: true }
)

Replace Existing Document with New Document

If the <update> argument contains only field and value pairs, the update() method replaces the existing document with the document in the <update> argument, except for the _id field.

The following operation queries the bios collection for the first document that has a name field equal to { first: 'John', last: 'McCarthy' } and replaces all but the _id field in the document with the fields in the <update> argument:

db.bios.update(
   { name: { first: 'John', last: 'McCarthy' } },
   { name: { first: 'Ken', last: 'Iverson' },
     born: new Date('Dec 17, 1941'),
     died: new Date('Oct 19, 2004'),
     contribs: [ 'APL', 'J' ],
     awards: [
               { award: 'Turing Award',
                 year: 1979,
                 by: 'ACM' },
               { award: 'Harry H. Goode Memorial Award',
                 year: 1975,
                 by: 'IEEE Computer Society' },
               { award: 'IBM Fellow',
                 year: 1970,
                 by: 'IBM' }
             ]
   }
)

Upsert

If you set the upsert option in the <options> argument to true or 1 and no existing document match the <query> argument, the update() method can insert a new document into the collection.

The following operation queries the bios collection for a document with the _id field equal to 11 and the name field equal to { first: 'James', last: 'Gosling'}. If the query selects a document, the operation performs an update operation. If a document is not found, update() inserts a new document containing the fields and values from <query> argument with the operations from the <update> argument applied. [1]

db.bios.update(
   { _id:11, name: { first: 'James', last: 'Gosling' } },
   {
     $set: {
             born: new Date('May 19, 1955'),
             contribs: [ 'Java' ],
             awards: [
                       {
                         award: 'The Economist Innovation Award',
                         year: 2002,
                         by: 'The Economist'
                       },
                       {
                         award: 'Officer of the Order of Canada',
                         year: 2007,
                         by: 'Canada'
                       }
                     ]
           }
   },
   { upsert: true }
)

See also Upsert in the 创建 section.

[1]If the <update> argument includes only field and value pairs, the new document contains the fields and values specified in the <update> argument. If the <update> argument includes only update operators, the new document contains the fields and values from <query> argument with the operations from the <update> argument applied.

Save

The save() method updates an existing document or inserts a document depending on the _id field of the document. The save() method is analogous to the update() method with the upsert option and a <query> argument on the _id field.

The save() method has the following syntax:

db.collection.save( <document> )

Save Performs an Update

If the <document> argument contains the _id field that exists in the collection, the save() method performs an update that replaces the existing document with the <document> argument.

The following operation queries the bios collection for a document where the _id equals ObjectId("507c4e138fada716c89d0014") and replaces the document with the <document> argument:

db.bios.save(
   {
     _id: ObjectId("507c4e138fada716c89d0014"),
     name: { first: 'Martin', last: 'Odersky' },
     contribs: [ 'Scala' ]
   }
)

也可以参考

Insert a Document with save() and Upsert with save() in the 创建 section.

Update Operators

按位

一致性

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务