diff --git a/snooty.toml b/snooty.toml index 12ebd493..3330ac44 100644 --- a/snooty.toml +++ b/snooty.toml @@ -3,6 +3,7 @@ title = "Go Driver" toc_landing_pages = [ "/connect", "/crud", + "/crud/update", "/monitoring-and-logging", "/security", "/security/authentication", diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index 4087759c..be821e2a 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -59,6 +59,8 @@ Find Operations Use **find operations** to retrieve data from MongoDB. Find operations consist of the ``Find()`` and ``FindOne()`` methods. +.. _golang-find-example: + Find All Documents ~~~~~~~~~~~~~~~~~~ @@ -66,72 +68,6 @@ The ``Find()`` method expects you to pass a ``Context`` type and a query filter. The method returns *all* documents that match the filter as a ``Cursor`` type. -For an example that uses the ``Find()`` method, see the :ref:`golang-find-example` -section of this page. To learn how to access data by using a cursor, see -the :ref:`golang-cursor` guide. - -Find One Document -~~~~~~~~~~~~~~~~~ - -The ``FindOne()`` method expects you to pass a ``Context`` type and a -query filter. The method returns *the first document* that matches the -filter as a ``SingleResult`` type. - -For an example that uses the ``FindOne()`` method, see the -:ref:`golang-find-one-example` section of this page. For an example that -uses ``FindOne()`` and queries by using a specific ``ObjectId`` value, see -the :ref:`golang-find-one-by-id` section of this page. - -To learn how to access data from a ``SingleResult`` type, see -:ref:`golang-bson-unmarshalling` in the BSON guide. - -.. _golang-retrieve-options: - -Modify Behavior -~~~~~~~~~~~~~~~ - -You can modify the behavior of ``Find()`` and ``FindOne()`` by passing -in a ``FindOptions`` and ``FindOneOptions`` type respectively. If you -don't specify any options, the driver uses the default values for each -option. - -You can configure the commonly used options in both types with the -following methods: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Method - - Description - - * - ``SetCollation()`` - - | The type of language collation to use when sorting results. - | Default: ``nil`` - - * - ``SetLimit()`` - - | The maximum number of documents to return. - | Default: ``0`` - | This option is not available for ``FindOneOptions``. The - ``FindOne()`` method internally uses ``SetLimit(-1)``. - - * - ``SetProjection()`` - - | The fields to include in the returned documents. - | Default: ``nil`` - - * - ``SetSkip()`` - - | The number of documents to skip. - | Default: ``0`` - - * - ``SetSort()`` - - | The field and type of sort to order the matched documents. You can specify an ascending or descending sort. - | Default: none - -.. _golang-find-example: - -Find Example -```````````` - The following example passes a context, filter, and ``FindOptions`` to the ``Find()`` method, which performs the following actions: @@ -155,10 +91,16 @@ the ``Find()`` method, which performs the following actions: {"item":"Sencha","rating":7,"date_ordered":"2009-11-18T05:00:00Z"} {"item":"Masala","rating":8,"date_ordered":"2009-12-01T05:00:00Z"} +To learn how to access data by using a cursor, see the :ref:`golang-cursor` guide. + .. _golang-find-one-example: -Find One Example -```````````````` +Find One Document +~~~~~~~~~~~~~~~~~ + +The ``FindOne()`` method expects you to pass a ``Context`` type and a +query filter. The method returns *the first document* that matches the +filter as a ``SingleResult`` type. The following example passes a context, filter, and ``FindOneOptions`` to the ``FindOne()`` method, which performs the following actions: @@ -182,6 +124,13 @@ to the ``FindOne()`` method, which performs the following actions: {"item":"Masala","rating":9,"date_ordered":"2009-11-12T05:00:00Z"} +For an example that +uses ``FindOne()`` and queries by using a specific ``ObjectId`` value, see +the :ref:`golang-find-one-by-id` section of this page. + +To learn how to access data from a ``SingleResult`` type, see +:ref:`golang-bson-unmarshalling` in the BSON guide. + .. _golang-find-one-by-id: Find One by ObjectId Example @@ -232,6 +181,48 @@ as parameters to the ``FindOne()`` method to perform the following actions: about the ``_id`` field, see the :ref:`_id Field ` section of the Insert a Document page. +.. _golang-retrieve-options: + +Modify Behavior +~~~~~~~~~~~~~~~ + +You can modify the behavior of ``Find()`` and ``FindOne()`` by passing +a ``FindOptions`` or ``FindOneOptions`` instance. If you +don't specify any options, the driver uses the default values for each +option. + +You can configure the commonly used options in both types with the +following methods: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``SetCollation()`` + - | The type of language collation to use when sorting results. + | Default: ``nil`` + + * - ``SetLimit()`` + - | The maximum number of documents to return. + | Default: ``0`` + | This option is not available for ``FindOneOptions``. The + ``FindOne()`` method internally uses ``SetLimit(-1)``. + + * - ``SetProjection()`` + - | The fields to include in the returned documents. + | Default: ``nil`` + + * - ``SetSkip()`` + - | The number of documents to skip. + | Default: ``0`` + + * - ``SetSort()`` + - | The field and type of sort to order the matched documents. You can specify an ascending or descending sort. + | Default: none + .. _golang-retrieve-aggregation: Aggregation Operations diff --git a/source/crud/update.txt b/source/crud/update.txt index 47e49fbb..5a6d1ef5 100644 --- a/source/crud/update.txt +++ b/source/crud/update.txt @@ -1,8 +1,9 @@ .. _golang-change-document: .. _golang-update: +.. _golang-update-documents: ================ -Modify Documents +Update Documents ================ .. facet:: @@ -29,13 +30,11 @@ Modify Documents Overview -------- -In this guide, you can learn how to modify documents in MongoDB using -**update** and **replace** operations. +In this guide, you can learn how to update documents in MongoDB by using +**update** operations. Update operations change the fields that you specify while leaving other -fields and values unchanged. Replace operations remove all existing fields -except for ``_id`` in a document and substitute the deleted fields with -the new fields and values you specify. +fields and values unchanged. In MongoDB, all methods to modify documents follow the same pattern: @@ -52,38 +51,29 @@ The pattern expects you to: * Specify the field and value changes. * Specify options, if you must modify the method behavior. -The driver provides the following methods to modify documents: +The driver provides the following methods to update documents: -* ``UpdateByID()`` -* ``UpdateOne()`` -* ``UpdateMany()`` -* ``ReplaceOne()`` -* ``BulkWrite()`` *(not discussed in this guide)* -* ``FindOneAndUpdate()`` *(not discussed in this guide)* -* ``FindOneAndReplace()`` *(not discussed in this guide)* +* ``UpdateByID()``: Updates a single document based on its ``_id``. +* ``UpdateOne()``: Updates a single document. +* ``UpdateMany()``: Updates multiple documents. -A Note About ``_id`` -~~~~~~~~~~~~~~~~~~~~ +A Note About _id +~~~~~~~~~~~~~~~~~ Each document in a MongoDB collection has a unique and immutable ``_id`` -field. You cannot use update and replace operations to change the -``_id`` field. If you attempt to change this field, the update and -replace methods return a ``WriteError``. - -.. _golang-update-documents: +field. You cannot use update operations to change the +``_id`` field. If you attempt to change this field, the update +methods return a ``WriteError``. -Update ------- +Sample Data +~~~~~~~~~~~ -Use the ``UpdateOne()`` or ``UpdateByID()`` method to update a single -document. -Use the ``UpdateMany()`` method to update multiple documents. .. _golang-update-document: Parameters -~~~~~~~~~~ +---------- Each method takes an **update document** that includes at least one **update operator**. The update operator specifies the type of update to perform. The update @@ -108,15 +98,15 @@ and descriptions `. .. note:: Aggregation Pipelines in Update Operations - If you are using MongoDB Server version 4.2 or later, you can use aggregation - pipelines made up of a subset of aggregation stages in update operations. To learn more about + You can use aggregation pipelines made up of a subset of aggregation + stages in update operations. To learn more about the aggregation stages MongoDB supports in aggregation pipelines, see our tutorial on performing :manual:`updates with aggregation pipelines `. Return Values -~~~~~~~~~~~~~ +------------- ``UpdateOne()``, ``UpdateByID()``, and ``UpdateMany()`` return an ``UpdateResult`` type that contains information about the update @@ -150,29 +140,34 @@ changes. See our :ref:`upsert guide ` to learn how to insert a new document if no documents match the query filter. -Example -``````` +UpdateOne() Example +------------------- -The following document describes an employee: +The following example uses the ``listingsAndReviews`` collection in the +``sample_airbnb`` dataset from the :atlas:`Atlas sample datasets `. +The following document describes an airbnb listing: .. code-block:: json :copyable: false { - "_id" : 2158, - "name" : "Mary Shelley", - "department" : "Marketing", - "role" : "Marketing Analyst", - "bonus" : 2500, + "_id": "10006546", + "listing_url": "https://www.airbnb.com/rooms/10006546", + "name": "Ribeira Charming Duplex", + "summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...", + ... + "minimum_nights": "2", + "maximum_nights": "30", + ... + "accommodates": 8, ... } -The following example uses the ``UpdateByID()`` method to: +The following example uses the ``UpdateOne()`` method to: -- Match the document where the ``_id`` value is 2158. -- Set the ``name`` field to "Mary Wollstonecraft Shelley" and the - ``role`` field to "Marketing Director". -- Increment the value of the ``bonus`` field by 2000. +- Match the document where the ``_id`` value is ``"10006546"``. +- Set the ``name`` field to ``"Ribiera River View Duplex"``. +- Increment the value of the ``accommodates`` field by ``1``. .. io-code-block:: :copyable: true @@ -180,9 +175,9 @@ The following example uses the ``UpdateByID()`` method to: .. input:: :language: go - filter := bson.D{{"_id", 2158}} - update := bson.D{{"$set", bson.D{{"name", "Mary Wollstonecraft Shelley"}, - {"role", "Marketing Director"}}}, {"$inc", bson.D{{"bonus", 2000}}}} + filter := bson.D{{"_id", "10006546"}} + update := bson.D{{"$set", bson.D{{"name", "Ribiera River View Duplex"}}}, + {"$inc", bson.D{{"accomodates", 1}}}} result, err := collection.UpdateOne(context.TODO(), filter, update) fmt.Printf("Documents matched: %v\n", result.MatchedCount) @@ -201,129 +196,49 @@ The following shows the updated document resulting from the preceding update ope :copyable: false { - "_id" : 2158, - "name" : "Mary Wollstonecraft Shelley", - "department" : "Marketing", - "role" : "Marketing Director", - "bonus" : 4500, + "_id": "10006546", + "listing_url": "https://www.airbnb.com/rooms/10006546", + "name": "Ribeira River View Duplex", + "summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...", + ... + "minimum_nights": "2", + "maximum_nights": "30", + ... + "accommodates": 9, ... } -.. _golang-replacement-document: - -Replace -------- - -Use the ``ReplaceOne()`` method to replace a single document. - -Parameters -~~~~~~~~~~ - -``ReplaceOne()`` expects a **replacement document**, which is the document -that you want to take the place of an existing document. Replacement -documents use the following format: - -.. code-block:: go - - bson.D{{"", ""}, {"", ""}, ... } - -Return Values -~~~~~~~~~~~~~ - -``ReplaceOne()`` returns an ``UpdateResult`` type that -contains information about the replace operation if the operation is -successful. The ``UpdateResult`` type contains the following properties: - -.. list-table:: - :widths: 30 70 - :header-rows: 1 - - * - Property - - Description - - * - ``MatchedCount`` - - The number of documents matched by the filter - - * - ``ModifiedCount`` - - The number of documents modified by the operation - - * - ``UpsertedCount`` - - The number of documents upserted by the operation - - * - ``UpsertedID`` - - The ``_id`` of the upserted document, or ``nil`` if there is none - -If multiple documents match the query filter passed to ``ReplaceOne()``, -the method selects and replaces the first matched document. Your replace -operation fails if no documents match the query filter. - -Example -``````` - -The following document describes a kitchen item: - -.. code-block:: json - :copyable: false - - { - "_id" : 2056, - "item" : "Mug", - "brand" : "Simply Ceramics", - "price" : 2.99, - "material" : "Glass" - } - -The following example uses the ``ReplaceOne()`` method to substitute -this document with one that contains an ``item`` field with a -value of "Cup" and a ``quantity`` field with a value of 107: - -.. io-code-block:: - :copyable: true - - .. input:: - :language: go - - filter := bson.D{{"_id", 2056}} - replacement := bson.D{{"item", "Cup"}, {"quantity", 107}} +UpdateMany() Example +-------------------- - result, err := collection.ReplaceOne(context.TODO(), filter, replacement) - fmt.Printf("Documents matched: %v\n", result.MatchedCount) - fmt.Printf("Documents replaced: %v\n", result.ModifiedCount) +The following example uses the ``listingsAndReviews`` collection in the +``sample_airbnb`` dataset from the :atlas:`Atlas sample datasets `. - .. output:: - :language: none - :visible: false +The following example uses the ``UpdateMany()`` method to: - Documents matched: 1 - Documents replaced: 1 +- Match documents in which the value of the ``address.market`` field is ``"Sydney"``. +- Multiply the ``price`` value in the matched documents by ``1.15`` -The replaced document contains the contents of the replacement document -and the immutable ``_id`` field as follows: +.. literalinclude:: /includes/usage-examples/code-snippets/updateMany.go + :start-after: begin updatemany + :end-before: end updatemany + :emphasize-lines: 9 + :language: go + :copyable: + :dedent: -.. code-block:: json - :copyable: false +The update operation updates ``609`` documents. - { - "_id" : 2056, - "item" : "Cup", - "quantity" : 107 - } +To learn more about how to retrieve multiple documents, see :ref:`golang-find-example`. Additional Information ---------------------- -For runnable examples of the update and replace operations, see the -following usage examples: - -- :ref:`golang-update-one` -- :ref:`golang-update-many` -- :ref:`golang-replacement-document` - To learn more about the operations mentioned, see the following guides: - :ref:`golang-query-document` -- :ref:`golang-upsert` +- :ref:`golang-retrieve` - :ref:`golang-compound-operations` - :manual:`Update Operators ` @@ -340,4 +255,3 @@ guide, see the following API Documentation: - `UpdateByID() <{+api+}/mongo#Collection.UpdateByID>`__ - `UpdateMany() <{+api+}/mongo#Collection.UpdateMany>`__ - `UpdateResult <{+api+}/mongo#UpdateResult>`__ -- `ReplaceOne() <{+api+}/mongo#Collection.ReplaceOne>`__ diff --git a/source/crud/update/upsert.txt b/source/crud/update/upsert.txt index f9dc2949..2b58049c 100644 --- a/source/crud/update/upsert.txt +++ b/source/crud/update/upsert.txt @@ -85,7 +85,7 @@ method in the options of the following write operation methods: equivalent to passing ``false`` to the ``SetUpsert()`` method. Example -~~~~~~~ +------- The following example performs the following actions: diff --git a/source/includes/usage-examples/code-snippets/updateMany.go b/source/includes/usage-examples/code-snippets/updateMany.go index 1acf729b..7e8578a7 100644 --- a/source/includes/usage-examples/code-snippets/updateMany.go +++ b/source/includes/usage-examples/code-snippets/updateMany.go @@ -46,10 +46,10 @@ func main() { if err != nil { panic(err) } - // end updatemany // Prints the number of updated documents fmt.Printf("Documents updated: %v\n", result.ModifiedCount) + // end updatemany // When you run this file for the first time, it should print: // Number of documents replaced: 609