Skip to content

DOCSP-51389 Add Go Specific Pages #534

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/redirects
Original file line number Diff line number Diff line change
Expand Up @@ -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/
1 change: 1 addition & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ name = "golang"
title = "Go Driver"
toc_landing_pages = [
"/connect",
"/context",
"/crud",
"/crud/update",
"/monitoring-and-logging",
Expand Down
1 change: 0 additions & 1 deletion source/archive-reference-files/fundamentals/context.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.. _golang-context:

=======
Context
Expand Down
1 change: 0 additions & 1 deletion source/archive-reference-files/usage-examples/findOne.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.. _golang-find-one:

===============
Find a Document
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.. _golang-struct-tags-usage-example:

===============
Use Struct Tags
Expand Down
1 change: 1 addition & 0 deletions source/connect.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Connection Guide
Choose a Connection Target </connect/connection-targets>
Connection Options </connect/specify-connection-options>
Connection Troubleshooting </connect/connection-troubleshooting>
Connect with AWS Lambda <https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/>

Overview
--------
Expand Down
131 changes: 131 additions & 0 deletions source/context.txt
Original file line number Diff line number Diff line change
@@ -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
<https://pkg.go.dev/context>`__ 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 <golang-readconcern>` 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("<db>").Collection("<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.
2 changes: 2 additions & 0 deletions source/crud/configure.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~

Expand Down
1 change: 1 addition & 0 deletions source/crud/query/retrieve.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.. _golang-retrieve:
.. _golang-find-one:

==============
Find Documents
Expand Down
1 change: 1 addition & 0 deletions source/data-formats.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Specialized Data Formats
:titlesonly:
:maxdepth: 1

Use Struct Tags </data-formats/struct-tagging>
BSON </data-formats/bson>
Extended JSON </data-formats/extended-json>

Expand Down
72 changes: 72 additions & 0 deletions source/data-formats/struct-tagging.txt
Original file line number Diff line number Diff line change
@@ -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 </reference/bson-types/>` 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?",

Check failure on line 52 in source/data-formats/struct-tagging.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidObscure] Use 'versus' instead of 'vs. '. Raw Output: {"message": "[MongoDB.AvoidObscure] Use 'versus' instead of 'vs. '.", "location": {"path": "source/data-formats/struct-tagging.txt", "range": {"start": {"line": 52, "column": 27}}}, "severity": "ERROR"}
"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 <golang-bson>` guide.

API Documentation
~~~~~~~~~~~~~~~~~

- `Structs and Struct Tags <{+api+}@{+full-version+}/bson#hdr-Structs>`__
- `InsertOne() <{+api+}/mongo#Collection.InsertOne>`__
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
1 change: 1 addition & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

Get Started </get-started>
Connect </connect>
Context Package </context>
Databases & Collections </databases-collections>
CRUD Operations </crud>
Aggregation </aggregation>
Expand Down
Loading