diff --git a/config/redirects b/config/redirects index 92439aca..3d87b336 100644 --- a/config/redirects +++ b/config/redirects @@ -20,3 +20,6 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-master]: ${prefix}/${version}/fundamentals/crud/write-read-pref/ -> ${base}/${version}/crud/configure/ [*-master]: ${prefix}/${version}/fundamentals/collations/ -> ${base}/${version}/crud/configure/ +# CC Redirects +[v1.12-master]: ${prefix}/${version}/usage-examples/struct-tagging/ -> ${base}/${version}/data-formats/struct-tagging/ +[v1.12-master]: ${prefix}/${version}/fundamentals/context/ -> ${base}/${version}/context/ diff --git a/snooty.toml b/snooty.toml index 7faaee53..96383e35 100644 --- a/snooty.toml +++ b/snooty.toml @@ -2,6 +2,7 @@ name = "golang" title = "Go Driver" toc_landing_pages = [ "/connect", + "/context", "/crud", "/crud/update", "/monitoring-and-logging", diff --git a/source/archive-reference-files/fundamentals/context.txt b/source/archive-reference-files/fundamentals/context.txt index b2487b0d..16f388ea 100644 --- a/source/archive-reference-files/fundamentals/context.txt +++ b/source/archive-reference-files/fundamentals/context.txt @@ -1,4 +1,3 @@ -.. _golang-context: ======= Context diff --git a/source/archive-reference-files/usage-examples/findOne.txt b/source/archive-reference-files/usage-examples/findOne.txt index 4d0e9737..b7b86617 100644 --- a/source/archive-reference-files/usage-examples/findOne.txt +++ b/source/archive-reference-files/usage-examples/findOne.txt @@ -1,4 +1,3 @@ -.. _golang-find-one: =============== Find a Document diff --git a/source/archive-reference-files/usage-examples/struct-tagging.txt b/source/archive-reference-files/usage-examples/struct-tagging.txt index 40a82b24..8e6aca07 100644 --- a/source/archive-reference-files/usage-examples/struct-tagging.txt +++ b/source/archive-reference-files/usage-examples/struct-tagging.txt @@ -1,4 +1,3 @@ -.. _golang-struct-tags-usage-example: =============== Use Struct Tags diff --git a/source/connect.txt b/source/connect.txt index cf27f34f..606918cc 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -28,6 +28,7 @@ Connection Guide Choose a Connection Target Connection Options Connection Troubleshooting + Connect with AWS Lambda Overview -------- diff --git a/source/context.txt b/source/context.txt new file mode 100644 index 00000000..56480a5e --- /dev/null +++ b/source/context.txt @@ -0,0 +1,131 @@ +.. _golang-context: + +=============== +Context Package +=============== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, unblock + :description: Learn how to use the context package in Go to manage timeouts and cancellations for blocking method calls in the MongoDB Go driver. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +The {+driver-short+} uses the `context package +`__ from the Go standard library to allow +applications to signal timeouts and cancellations for any **blocking method** +call. A blocking method relies on an external event, such as a network +input or output, to proceed with its task. + +An example of a blocking method is the ``InsertOne()`` +method. If you want to perform an insert operation on a ``Collection`` +within 10 seconds, you can use a Context with a timeout. If the +operation doesn't complete within the timeout, the method returns +an error. + +.. code-block:: go + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + client.Database("db").Collection("items").InsertOne(ctx, bson.D{{"x",1}}) + +If the Context passed into an operation does not have a deadline, you +can set a ``Timeout`` option on your ``Client`` and the operation +derives the timeout specification from this setting. To learn more +about using the single timeout setting, see the +:ref:`golang-timeout-setting` in the Connection Options guide. + +Expiration +---------- + +The driver considers a Context expired when an operation exceeds its +timeout or is canceled. The driver checks the Context expiration with +the ``Done()`` method. + +The following sections describe when and how the driver checks for +expiration. + +Server Selection +~~~~~~~~~~~~~~~~ + +The driver might block a method call if it can't select a server for +an operation. + +In this scenario, the driver loops until it finds a server to use for the +operation. After each iteration, the driver returns a server selection +timeout error if the Context expired or the selection process took +longer than the ``serverSelectionTimeoutMS`` setting. + +To learn more about how the driver selects a server, see the +:ref:`Read Concern ` section in the Configure +CRUD Operations guide. + +Connection Checkout +~~~~~~~~~~~~~~~~~~~ + +The driver might block a method call if there are no available +connections to check out. + +After selecting a server, the driver tries to check out a connection +from the server's connection pool. If the Context expires while checking +out a connection, the method returns a timeout error. + +Connection Establishment +~~~~~~~~~~~~~~~~~~~~~~~~ + +The driver might block a method call if it must create a new +connection. + +When the driver creates a new connection to perform an operation, the +Context sets a timeout for the establishment process. The driver sets the +timeout to either the Context expiration or connection timeout, whichever is +shorter. + +The following example sets the connection timeout to *1* second and the +Context deadline to *2* seconds. Because the connection timeout is +shorter, the establishment process expires after *1* second. + +.. code-block:: go + :emphasize-lines: 2, 5 + + opts := options.Client() + opts.SetConnectTimeout(1*time.Second) + client, err := mongo.Connect(opts) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + client.Database("").Collection("").InsertOne(ctx, bson.D{{"x",1}}) + +Socket Read and Write +~~~~~~~~~~~~~~~~~~~~~ + +When the driver retrieves a connection for an operation, it sets the +socket's read or write deadline to either the Context deadline or socket +timeout, whichever is shorter. + +If you cancel the Context after the execution of the ``Read()`` or +``Write()`` method but before its deadline, the behavior of the driver +differs based on version. + +The driver generates a separate goroutine to listen for Context +cancellation when the ``Read()`` or ``Write()`` method is in progress. +If the goroutine detects a cancellation, it closes the connection. The +pending ``Read()`` or ``Write()`` method returns an error which the +driver overwrites with the ``context.Canceled`` error. + +.. important:: + + In versions before 1.5.0, the driver doesn't detect the Context + cancellation and waits for the ``Read()`` or ``Write()`` method to + return. diff --git a/source/crud/configure.txt b/source/crud/configure.txt index d6fecb8a..f14d19cd 100644 --- a/source/crud/configure.txt +++ b/source/crud/configure.txt @@ -179,6 +179,8 @@ acknowledgement from the majority of replica set members. collOpts := options.Collection().SetWriteConcern(collWC) coll := client.Database("db").Collection("myColl", collOpts) +.. _golang-readconcern: + Read Concern ~~~~~~~~~~~~ diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index be821e2a..ae6603f3 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -1,4 +1,5 @@ .. _golang-retrieve: +.. _golang-find-one: ============== Find Documents diff --git a/source/data-formats.txt b/source/data-formats.txt index 32652527..d6194b89 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -26,6 +26,7 @@ Specialized Data Formats :titlesonly: :maxdepth: 1 + Use Struct Tags BSON Extended JSON diff --git a/source/data-formats/struct-tagging.txt b/source/data-formats/struct-tagging.txt new file mode 100644 index 00000000..99b08837 --- /dev/null +++ b/source/data-formats/struct-tagging.txt @@ -0,0 +1,72 @@ +.. _golang-struct-tags-usage-example: + +=============== +Use Struct Tags +=============== + +.. meta:: + :description: Learn how to use struct tags in Go to control BSON field names when inserting documents with the MongoDB Go Driver. + +You can specify the way that the Go Driver converts Go +structs to :manual:`BSON ` by using struct tags. + +Example +------- +.. TODO: Add the Usage Examples intro include once it is merged + +The following code declares a struct of type ``BlogPost``. This struct +contains a struct tag that maps the ``WordCount`` field to the BSON +field name ``word_count``. By default, the driver marshals the other +fields as the lowercase of the struct field name: + +.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go + :start-after: begin struct + :end-before: end struct + :language: go + :dedent: + +The following example creates a ``BlogPost`` instance and inserts it +into the ``posts`` collection. During the insert operation, the driver +interprets the struct tag to marshal the ``WordCount`` +struct field as ``word_count``: + +.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go + :start-after: begin create and insert + :end-before: end create and insert + :language: go + :dedent: + +View a `fully runnable example. <{+example+}/struct-tag.go>`__ + +Expected Result +--------------- + +After you run the full example, you can find the following document +in the ``posts`` collection: + +.. code-block:: json + :copyable: false + + { + "_id" : ObjectId("..."), + "title" : "Annuals vs. Perennials?", + "author" : "Sam Lee", + "word_count" : 682, + "lastupdated": ..., + "tags" : ["seasons", "gardening", "flower"] + } + +For an example on how to find a document, see the :ref:`golang-find-one` guide. + +Additional Information +---------------------- + +To learn more about using struct tags, converting to/from BSON, and +handling potential errors, see the :ref:`Work with BSON ` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +- `Structs and Struct Tags <{+api+}@{+full-version+}/bson#hdr-Structs>`__ +- `InsertOne() <{+api+}/mongo#Collection.InsertOne>`__ +- `FindOne() <{+api+}/mongo#Collection.FindOne>`__ diff --git a/source/index.txt b/source/index.txt index b4a27204..e958abc9 100644 --- a/source/index.txt +++ b/source/index.txt @@ -18,6 +18,7 @@ Get Started Connect + Context Package Databases & Collections CRUD Operations Aggregation