Modify Documents

Modify Documents

In MongoDB, both db.collection.update() and db.collection.save() modify existing documents in a collection. db.collection.update() provides additional control over the modification. For example, you can modify existing data or modify a group of documents that match a query with db.collection.update(). Alternately, db.collection.save() replaces an existing document with the same _id field.

Modify Multiple Documents with update() Method – By default, the update() method updates a single document that matches its selection criteria. Call the method with the multi option set to true to update multiple documents. The following example finds all documents with type equal to “book” and modifies their qty field by -1. The example uses $inc, which is one of the update operators available.

db.inventory.update(

{ type : “book” },

{ $inc : { qty : -1 } },

{ multi: true }

)

Modify a Document with save() Method – The save() method can replace an existing document. To replace a document with the save() method, pass the method a document with an _id field that matches an existing document. The following example completely replaces the document with the _id equal to 10 in the inventory collection:

db.inventory.save(

{

_id: 10,

type: “misc”,

item: “placard”

}

)

Apply for MongoDB Certification Now!!

https://www.vskills.in/certification/databases/mongodb-server-administrator

Back to Tutorial

Share this post
[social_warfare]
Write Operations
Remove Documents

Get industry recognized certification – Contact us

keyboard_arrow_up