Updating documents using the mongo-ruby-driver is chained to finding them. Using our example collection books, we can do:
@collection.update_one( { 'isbn': 101}, { '$set' => { name: 'Mastering MongoDB, 2nd Edition' } } )
This finds the document with isbn 101 and changes its name to Mastering MongoDB, 2nd Edition.
Similar to update_one, we can use update_many to update multiple documents retrieved via the first parameter of the method.
Assuming Ruby version >=2.2 , keys can be unquoted or quoted, but keys that start with $ need to be quoted like this:
@collection.update( { isbn: '101'}, { "$set": { name: "Mastering MongoDB, 2nd edition" } } )
The resulting object of an update will contain information about the operation, including these methods:
- ok?: A Boolean value that shows whether the operation was successful or not
- matched_count: The number of documents matching the query
- modified_count: The number of documents affected (updated)
- upserted_count: The number of documents upserted if the operation includes $set
- upserted_id: The unique ObjectId of the upserted document if there is one
Updates that modify fields of a constant data size will be in place, meaning that they won't move the document from its physical location on disk. This includes, for example, operations such as $inc and $set on the Integer and Date fields.
Updates that can increase the size of a document may result in the document being moved from its physical location on disk to a new location at the end of the file. In this case, queries may miss or return the document multiple times. To avoid this, we can use $snapshot: true while querying.