2 ways MongoDB can modify data

  • 2020-05-10 23:06:28
  • OfStack

In MongoDB, both the db.collection.ipdate () and db.collection.save () methods can modify existing documents in the collection. The db.collection.update () method provides additional control over modifications. For example, db.collectoin.update () modifies existing data or a set of documents that match query conditions. The db.collection.save () method replaces one existing document with the same _id.

Modify multiple documents using the update() method:

By default, the update() method updates 1 document that meets the criteria. Multiple documents can be modified by setting the multi option to true when calling a method. The following example modifies the qty field of all documents with an type field value of "book" to increase -1. The example USES $inc, which is a modification operator variable.


db.inventory.update(
   { type : "book" },
   { $inc : { qty : -1 } },
   { multi: true }
)

Modify a document using the save() method:

The save() method replaces an existing document. Replace one document with the save() method, which matches one existing document with the _id field. The following example completely replaces a document with _id of 10 in the inventory collection:


db.inventory.save(
   {
     _id: 10,
     type: "misc",
     item: "placard"
   }
)


Related articles: