Mongodb-mongodb CRUD Operations, Update Documents

Source: Internet
Author: User


Update Methods


MongoDB provides the following methods for updating documents in a collection:


Method Description
Db.collection.updateOne ()

Updates at more than a single document that match a specified filter even though multiple documents may match the specified Fil ter.

New in version 3.2.

Db.collection.updateMany ()

Update All documents that match a specified filter.

New in version 3.2.

Db.collection.replaceOne ()

Replaces at more a single document this match a specified filter even though multiple documents may match the specified fi Lter.

New in version 3.2.

Db.collection.update ()

Either updates or replaces a single document this match a specified filter or updates all documents that match a specified Filter.

By default, thedb.collection.update ()method updates a single document. To update multiple documents, use the multi option.


These methods accept as parameters:


  • a filter document to determine which documents to update. These filters use the same syntax as read operations:
    • a query Filter Document can Specify Equality condition WITH&NBSP;<FIELD>:<VALUE>  expressions To select all documents that contain THE&NBSP; <field>  with the specified <value :
       {<field1>: <value1>, ...} 
    • a query filter Document can use the query operators to specify conditions in the following form:< pre>{<field1>: {<operator1>: <value1>}, ...}
  • An update document to specify the modification to perform or a replacement document that wholly replaces the matching docu ments except for the_idfield, and
  • An options document.




Behavioratomicity


All write operations in MongoDB is atomic on the level of a single document. For more information in MongoDB and atomicity, see Atomicity and transactions.


_idField


Once set, you cannot update the value of the_idfield or can you replace an existing document with a Replacemen T document that has a different_idfield value.


Document Size


When performing update operations. Increase the document size beyond the allocated space for that document, the update Operation relocates the document on disk.


Field Order


MongoDB preserves the order of the document fields following write operations except for the following cases:


    • The_idfield is always the first field in the document.
    • Updates This includerenamingof field names may result in the reordering of the the document.


Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the "in a" document.


UpsertOption


Ifdb.collection.update (),Db.collection.updateOne (),db.collection.updateMany (), orDb.collection.replaceOne ()includes upsert:true and no documents match the specified filter, then the Operation creates a new document and inserts it. If there is matching documents, then the operation modifies or replaces the matching document or documents.



For details on the new document created, see the individual reference pages for the methods.





Example Collection


The examples on this page with theDb.collection.find ()method in theMONGOshell. In theMONGOShell, if the returned cursor was not assigned to a variable using thevarkeyword and then the Cursor is automatically iterated-to-the-print up-to-the-first documents in the results.



To populate theuserscollection referenced in the examples, run the following inMONGOShell:



Note:  if the users  collection already contains documents with the SAME&NBSP;_id  values, you need to drop  the Collection (db.users.drop () ) before inserting The example documents.


db.users.insertMany(
   [
     {
       _id: 1,
       name: "sue",
       age: 19,
       type: 1,
       status: "P",
       favorites: { artist: "Picasso", food: "pizza" },
       finished: [ 17, 3 ],
       badges: [ "blue", "black" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 85, bonus: 10 }
       ]
     },
     {
       _id: 2,
       name: "bob",
       age: 42,
       type: 1,
       status: "A",
       favorites: { artist: "Miro", food: "meringue" },
       finished: [ 11, 25 ],
       badges: [ "green" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 64, bonus: 12 }
       ]
     },
     {
       _id: 3,
       name: "ahn",
       age: 22,
       type: 2,
       status: "A",
       favorites: { artist: "Cassatt", food: "cake" },
       finished: [ 6 ],
       badges: [ "blue", "Picasso" ],
       points: [
          { points: 81, bonus: 8 },
          { points: 55, bonus: 20 }
       ]
     },
     {
       _id: 4,
       name: "xi",
       age: 34,
       type: 2,
       status: "D",
       favorites: { artist: "Chagall", food: "chocolate" },
       finished: [ 5, 11 ],
       badges: [ "Picasso", "black" ],
       points: [
          { points: 53, bonus: 15 },
          { points: 51, bonus: 15 }
       ]
     },
     {
       _id: 5,
       name: "xyz",
       age: 23,
       type: 2,
       status: "D",
       favorites: { artist: "Noguchi", food: "nougat" },
       finished: [ 14, 6 ],
       badges: [ "orange" ],
       points: [
          { points: 71, bonus: 20 }
       ]
     },
     {
       _id: 6,
       name: "abc",
       age: 43,
       type: 1,
       status: "A",
       favorites: { food: "pizza", artist: "Picasso" },
       finished: [ 18, 12 ],
       badges: [ "black", "blue" ],
       points: [
          { points: 78, bonus: 8 },
          { points: 57, bonus: 7 }
       ]
     }
   ]
)
View Code




Update specific fields in a Document


To change a field in a document, MongoDB provides update operators, such as$setto modify values.



To specify the modification to perform using update operators, use an update document of the form:


{
   <update operator>: { <field1>: <value1>, ... },
   <update operator>: { <field2>: <value2>, ... },
   ...
}


Some update operators, such as$set, would create the field if the field does not exist. See the individual update operator reference.


Db.collection.updateOne ()


New in version 3.2.



The following example uses THE&NBSP; Db.collection.updateOne ()  method on the  Users  collection to update the , first  document that matches the FILTER&NBSP;favorites.artist  equals  "Picasso" . The update operation:


    • uses the $set  operator to update the value of THE&NBSP;favorites.food field TO&NBSP;"pie" and the value of the type field to &NBSP;3,
    • uses the $currentDate operator to update the value of THE&NBSP;lastmodified field to the current date. IF&NBSP;lastmodified field does not exist, $currentDate will create the field. See$currentDate for details.
db.users.updateOne(
   { "favorites.artist": "Picasso" },
   {
     $set: { "favorites.food": "pie", type: 3 },
     $currentDate: { lastModified: true }
   }
)


For more information and examples, seedb.collection.updateOne ().


Db.collection.updateMany ()


New in version 3.2.



The following example uses theDb.collection.updateMany ()method on theuserscollection to update all Documents that matches the filterfavorites.artistequals"Picasso". The update operation:


    • uses the $set  operator to update the value of THE&NBSP;favorites.artist field to "Pisanello" and the value of the type field to 3,
    • uses the $currentDate operator to update the value of THE&NBSP;lastmodified field to the current date. IF&NBSP;lastmodified field does not exist, $currentDate will create the field. See$currentDate for details.
db.users.updateMany(
   { "favorites.artist": "Picasso" },
   {
     $set: { "favorites.artist": "Pisanello", type: 3 },
     $currentDate: { lastModified: true }
   }
)


For more information and examples, seedb.collection.updateMany ().


db.collection.update


The following example uses thedb.collection.update ()method on theuserscollection to update thefirst document that matches the filterfavorites.artistequals"Pisanello". The update operation:


    • uses the $set  operator to update the value of THE&NBSP;favorites.food field TO&NBSP;"pizza" and the value of the type field to &NBSP;0,
    • uses the $currentDate operator to update the value of THE&NBSP;lastmodified field to the current date. IF&NBSP;lastmodified field does not exist, $currentDate will create the field. See$currentDate for details.
db.users.update(
   { "favorites.artist": "Pisanello" },
   {
     $set: { "favorites.food": "pizza", type: 0,  },
     $currentDate: { lastModified: true }
   }
)


To update multiple documents using thedb.collection.update (), include the multi:true option:


db.users.update(
   { "favorites.artist": "Pisanello" },
   {
     $set: { "favorites.food": "pizza", type: 0,  },
     $currentDate: { lastModified: true }
   },
   { multi: true }
)




Replace the Document


To replace the entire content of a document except for the_idfield, pass an entirely new document as the second Argument toDb.collection.replaceOne ()ordb.collection.update (). When replacing a document, the replacement document must consist of only <field>: <value>.



The replacement document can has different fields from the original document. In the replacement document, you can omit the_idfield since the_idfield is immutable; However, if you do include the_idfield, it must has the same value as the current value.


Db.collection.replaceOne


The following example uses theDb.collection.replaceOne ()method on theuserscollection to replace the first document that matches the filternameequals"abc" with thenew document:


db.users.replaceOne(
   { name: "abc" },
   { name: "amy", age: 34, type: 2, status: "P", favorites: { "artist": "Dali", food: "donuts" } }
)
db.collection.update


The following example uses thedb.collection.update ()method on theuserscollection to replace the first document that matches the filternameequals"xyz" with thenew document:


db.users.update(
   { name: "xyz" },
   { name: "mee", age: 25, type: 1, status: "A", favorites: { "artist": "Matisse", food: "mango" } }
)




Additional Methods


The following methods can also update documents from a collection:


    • db.collection.findOneAndReplace ().
    • db.collection.findOneAndUpdate ().
    • db.collection.findAndModify ().
    • Db.collection.save ().
    • db.collection.bulkWrite ().


See the individual reference pages for the methods for more information and examples.





Write Acknowledgement


With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.






Mongodb-mongodb CRUD Operations, Update Documents


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.