Updating documents using mongo-ruby-driver is chained to finding them. Using our example books collection, we can do the following:
@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.
In a similar way 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 either quoted or unquoted; however, keys that start with $ need to be quoted as follows:
@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; this means that they won't move the document from its physical location on the disk. This includes 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 the 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.