Updating Documents in a Collection

Typically you update documents in a collection through your Node.js application. However, at times you may need to manually update a document from an administrative point of view to fix a database or for testing purposes.

To update documents in a collection, you need to get the collection. Then you can use the save(object) method to save changes you have made to an object. Or you can use the update(query, update, options) method to query for documents in the collection and then update them as they are found.

When you use the update() method, the query parameter specifies a query document with fields and values to match documents against in the collection. The update parameter is an object that specifies the update operator to use when making the update. For example, $inc increments the value of the field, $set sets the value of the field, $push pushes an item onto an array, etc. For example, the following update object increments one field, sets another, and then renames a third:

{ $inc: {count: 1}, $set: {name: "New Name"}, $rename: {"nickname": "alias"} }

The options parameter of update() is an object that has two properties—multi and upsert—that are both Boolean values. If upsert is true, a new document is created if none are found. If multi is true, all documents that match the query are updated; otherwise, only the first document is updated.

For example, the following commands update documents with a speed of 120mph by setting the speed to 150 and adding a new field called updated. Also, the save() method is used to save changes to the plane document:

use testDB
coll = db.getCollection("newCollection")
coll.find()
coll.update({ speed: "120mph" },
            { $set: { speed: "150mph" , updated: true } },
            { upsert: false, multi: true })
coll.save({ "_id" : ObjectId("52a0caf33120fa0d0e424ddb"),
            "vehicle" : "plane", "speed" : "500mph" })
coll.find()

Figure 12.12 shows the console output.

Image

Figure 12.12 Updating documents from a collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.72