UpdatesUpdates can be one of the most complicated operation available with MongoDB. They combine a query with an action, modifying documents that match the criteria. They are also extremely powerful, allowing you to change documents quickly and replace them altogether. They are done in-place (when possible) with little overhead. Modifying vs. replacing documentsThere are two types of updates you can use: modifying updates and replacing updates. Modifying updates contain $-operators and change fields in a document: they might increment counters, push new elements onto an array, or change the type of a field. For example, a modifying update could add a new field to a document.
<?php Replacing updates replace the entire matching document with a new document. They are generally not as efficient as using $-modifiers, but can be very usefully for complex operations or updates that can't be expressed in terms of $-operators. For example, a replacing update can completely change the structure of a document.
<?php Updating Nested ObjectsSuppose we wish to change the name of a comment's author in this document: { "_id" : ObjectId("4b06c282edb87a281e09dad9"), "content" : "this is a blog post.", "comments" : [ { "author" : "Mike", "comment" : "I think that blah blah blah...", }, { "author" : "John", "comment" : "I disagree." } ] }
<?php The Positional OperatorThe positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.
<?php |