Skip to content

DOCSP-47019 Shift Go ToC #499

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

Open
wants to merge 4 commits into
base: comp-cov
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions snooty.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
name = "golang"
title = "Go Driver"
toc_landing_pages = [
"/fundamentals/connections",
"/fundamentals/crud",
"/usage-examples",
"/connect",
"/crud",
"/monitoring-and-logging",
"/security"
]

intersphinx = [
Expand Down
File renamed without changes.
192 changes: 192 additions & 0 deletions source/archive-reference-files/faq.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
.. _golang-faq:

===
FAQ
===

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code example, connection error, question, help
:description: Find answers to common questions about the MongoDB Go Driver, including connection pooling, error handling, and BSON to JSON conversion.

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

This page contains frequently asked questions and their corresponding answers.

.. tip::

If you can't find an answer to your problem on this page,
see the :ref:`golang-issues-and-help` page for next steps and more
resources.

Why Am I Getting Errors While Connecting to MongoDB?
----------------------------------------------------

If you have trouble connecting to a MongoDB deployment, see
the :ref:`Connection Troubleshooting Guide <golang-connection-troubleshooting>`
for possible solutions.

.. _golang-faq-connection-pool:

How Does Connection Pooling Work in the {+driver-short+}?
---------------------------------------------------------

Every ``Client`` instance has a built-in connection pool for each server
in your MongoDB topology. Connection pools open sockets on demand to support
concurrent MongoDB operations, or `goroutines
<https://www.golang-book.com/books/intro/10>`__, in your application.

The maximum size of each connection pool is set by the ``maxPoolSize`` option, which
defaults to ``100``. If the number of in-use connections to a server reaches
the value of ``maxPoolSize``, the next request to that server will wait
until a connection becomes available.

The ``Client`` instance opens two additional sockets per server in your

Check failure on line 51 in source/archive-reference-files/faq.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/archive-reference-files/faq.txt", "range": {"start": {"line": 51, "column": 35}}}, "severity": "ERROR"}
MongoDB topology for monitoring the server's state.

For example, a client connected to a 3-node replica set opens 6
monitoring sockets. It also opens the necessary sockets to support
an application's concurrent operations on each server, up to
the value of ``maxPoolSize``. If ``maxPoolSize`` is ``100`` and the
application only uses the primary (the default), then only the primary
connection pool grows and there can be at most ``106`` total connections. If the
application uses a :ref:`read preference <golang-read-pref>` to query the
secondary nodes, their pools also grow and there can be ``306`` total connections.

Additionally, connection pools are rate-limited such that each connection pool
can only create, at maximum, the value of ``maxConnecting`` connections
in parallel at any time. Any additional goroutine stops waiting in the

Check failure on line 65 in source/archive-reference-files/faq.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/archive-reference-files/faq.txt", "range": {"start": {"line": 65, "column": 30}}}, "severity": "ERROR"}
following cases:

- One of the existing goroutines finishes creating a connection, or
an existing connection is checked back into the pool.
- The driver's ability to reuse existing connections improves due to
rate-limits on connection creation.

You can set the minimum number of concurrent connections to
each server by using the ``minPoolSize`` option, which defaults to ``0``.
After setting ``minPoolSize``, the connection pool is initialized with
this number of sockets. If sockets close due to any network errors, causing
the total number of sockets (both in use and idle) to drop below the minimum, more sockets
open until the minimum is reached.

You can set the maximum number of milliseconds that a connection can
remain idle in the pool before being removed and replaced with
the ``maxIdleTimeMS`` option, which defaults to ``None`` (no limit).

The following default configuration for a ``Client`` works for most applications:

.. code-block:: go

client, err := mongo.Connect(options.Client().ApplyURI("<connection string>"))

Create a client once for each process, and reuse it for all
operations. It is a common mistake to create a new client for each
request, which is very inefficient.

To support high numbers of concurrent MongoDB operations
within one process, you can increase ``maxPoolSize``. Once the pool
reaches its maximum size, additional operations wait for sockets

Check failure on line 96 in source/archive-reference-files/faq.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/archive-reference-files/faq.txt", "range": {"start": {"line": 96, "column": 27}}}, "severity": "ERROR"}
to become available.

The driver does not limit the number of operations that
can wait for sockets to become available and it is the application's
responsibility to limit the size of its pool to bound queuing
during a load spike. Operations can wait for any length of time
unless you define the ``waitQueueTimeoutMS`` option.

An operation that waits more than the length of time defined by
``waitQueueTimeoutMS`` for a socket raises a connection error. Use this
option if it is more important to bound the duration of operations
during a load spike than it is to complete every operation.

When ``Client.Disconnect()`` is called by any goroutine, the driver
closes all idle sockets and closes all sockets that are in
use as they are returned to the pool.

How Can I Fix the "WriteNull can only write while positioned on a Element or Value but is positioned on a TopLevel" Error?
--------------------------------------------------------------------------------------------------------------------------

The ``bson.Marshal()`` method requires a parameter that can be decoded
into a BSON document, such as the ``bson.D`` type. This error occurs
when you pass something *other* than a BSON document to
``bson.Marshal()``.

The ``WriteNull`` error occurs when you pass a ``null`` to
``bson.Marshal()``. Situations in which a similar error can occur
include the following:

- You pass a string to ``bson.Marshal()``, causing a ``WriteString`` error.
- You pass a boolean to ``bson.Marshal()``, causing a ``WriteBoolean`` error.
- You pass an integer to ``bson.Marshal()``, causing a ``WriteInt32`` error.

You may encounter this error when you perform a CRUD operation that
internally uses the ``bson.Marshal()`` method or when you call
``bson.Marshal()`` directly to encode data.

The following code produces a ``WriteNull`` error because the driver
cannot encode the ``null`` value of ``sortOrder`` to BSON during
the ``FindOneAndUpdate()`` operation:

.. code-block:: go

var sortOrder bson.D
opts := options.FindOneAndUpdate().SetSort(sortOrder)

updateDocument := bson.D{{"$inc", bson.D{{"counter", 1}}}}
result := coll.FindOneAndUpdate(context.TODO(), bson.D{}, updateDocument, opts)
if err := result.Err(); err != nil {
panic(err)
}

The following code shows how to correctly initialize the ``sortOrder``
variable as a ``bson.D`` type so that the driver can convert it to BSON:

.. code-block:: go

sortOrder := bson.D{}

How Do I Convert a BSON Document to JSON?
-----------------------------------------

The driver provides a variety of marshaler methods that can be used to
convert a BSON document to JSON, such as the ``MarshalExtJSON()``
method. To view a readable form of the JSON encoding, you must use
an unmarshaler method or string type-casting to parse the JSON byte
format.

The following code converts a BSON document to JSON using the
``MarshalExtJSON()`` method, then parses and prints the JSON byte array
using string type-casting:

.. io-code-block::
:copyable: true

.. input::
:language: go
:emphasize-lines: 3

bsonDocument := bson.D{{"hello", "world"}}

jsonBytes, err := bson.MarshalExtJSON(bsonDocument, true, false)
if err != nil {
panic(err)
}

fmt.Println(string(jsonBytes))

.. output::
:language: none
:visible: false

{"hello":"world"}

To learn more about conversions between BSON and Go types, see the
:ref:`golang-bson` guide.
File renamed without changes.
56 changes: 56 additions & 0 deletions source/archive-reference-files/issues-and-help.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
.. _golang-issues-and-help:

=============
Issues & Help
=============

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: suggestion, github
:description: Find support for the MongoDB Go Driver through community forums, report bugs or feature requests via JIRA, and create pull requests to contribute.

Check failure on line 13 in source/archive-reference-files/issues-and-help.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidObscure] Use 'through, by' instead of 'via'. Raw Output: {"message": "[MongoDB.AvoidObscure] Use 'through, by' instead of 'via'.", "location": {"path": "source/archive-reference-files/issues-and-help.txt", "range": {"start": {"line": 13, "column": 115}}}, "severity": "ERROR"}

We are lucky to have a vibrant MongoDB Go community that includes users
with varying levels of experience using the Go driver. We find the quickest
way to get support for general questions is through the `MongoDB Community Forums <https://community.mongodb.com>`_.

To learn more, refer to our `support channels <http://www.mongodb.org/about/support>`_.

Check failure on line 19 in source/archive-reference-files/issues-and-help.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'see' is preferred over 'refer to'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'see' is preferred over 'refer to'.", "location": {"path": "source/archive-reference-files/issues-and-help.txt", "range": {"start": {"line": 19, "column": 16}}}, "severity": "ERROR"}

Bugs / Feature Requests
-----------------------

If you think you've found a bug or want to see a new feature in the Go
driver, please open a case in our issue management tool, JIRA:

* `Create an account and log in <https://jira.mongodb.org>`_.
* Navigate to `the GODRIVER project <https://jira.mongodb.org/browse/GODRIVER>`_.
* Click **Create Issue**. Please provide as much information as possible
about the issue and the steps to reproduce it.

Bug reports in JIRA for the Go driver and the Core Server (i.e. SERVER) project are **public**.

Check failure on line 32 in source/archive-reference-files/issues-and-help.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidObscure] Use 'that is' instead of 'i.e. '. Raw Output: {"message": "[MongoDB.AvoidObscure] Use 'that is' instead of 'i.e. '.", "location": {"path": "source/archive-reference-files/issues-and-help.txt", "range": {"start": {"line": 32, "column": 60}}}, "severity": "ERROR"}

If you've identified a security vulnerability in a driver or any other
MongoDB project, please report it according to the instructions found in the
:manual:`Create a Vulnerability Report page </tutorial/create-a-vulnerability-report>`.

Pull Requests
-------------

We are happy to accept contributions to help improve the driver. We will guide
user contributions to ensure they meet the standards of the codebase. Please
ensure that any pull requests include documentation, tests, and pass the
**gradle** checks.

To get started, check out the source and work on a branch:

.. code-block:: bash

$ git clone https://github.com/mongodb/mongo-go-driver.git
$ cd mongo-go-driver
$ git checkout -b myNewFeature

Finally, follow the `Testing/Development guidelines
<https://github.com/mongodb/mongo-go-driver#testing--development>`__ to
ensure your code passes any newly added and existing tests.
117 changes: 117 additions & 0 deletions source/archive-reference-files/quick-start.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
.. _golang-quickstart:

=====================
Go Driver Quick Start
=====================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: tutorial

.. meta::
:keywords: tutorial, get started, code example
:description: Learn to connect a Go application to a MongoDB Atlas cluster using the MongoDB Go Driver, including setting up a project, creating a cluster, and running queries.

.. include:: /includes/quick-start/overview.rst

Set Up Your Project
-------------------

.. procedure::
:style: connected

.. step:: Create and initialize your project

Create a new directory and initialize your project by using ``go mod``, as
shown in the following commands:

.. code-block:: shell

mkdir go-quickstart
cd go-quickstart
go mod init go-quickstart

.. step:: Add the {+driver-long+} as a dependency

Use ``go get`` to add the {+driver-short+} as a dependency, as shown in
the following command:

.. code-block:: shell

go get go.mongodb.org/mongo-driver/v2/mongo

Create a MongoDB Cluster
------------------------

.. include:: /includes/quick-start/atlas-setup.rst

Query Your MongoDB Cluster from Your Application
------------------------------------------------

.. procedure::
:style: connected

.. step:: Add your connection string

In your terminal, run the following command to create an environment
variable called ``MONGODB_URI`` and set your Atlas connection string as
its value:

.. code-block:: bash

export MONGODB_URI='<your atlas connection string>'

.. note::

Make sure to replace the ``<db_password>`` section of the connection
string with the password you created for your user that has
**atlasAdmin** permissions.

.. step:: Create a new file

Run the following command from the base directory of your project to
create a new file called ``main.go``:

.. code-block:: shell

touch main.go

.. step:: Create your Go application

Copy and paste the following code into your ``main.go`` file. This code
runs a query on your sample dataset in MongoDB Atlas.

.. literalinclude:: /includes/quick-start/main.go
:language: go
:dedent:

.. step:: Run your application

Run the sample code with the following command from your command line:

.. code-block:: bash

go run main.go

.. include:: /includes/quick-start/query-output.rst

.. tip::

If you receive no output or an error, check whether you properly set up
your environment variable and ensure you have loaded the
:atlas:`sample datasets </sample-data/>` into your cluster.

After you complete these steps, you have a working application that uses
the {+driver-long+} to connect to your MongoDB cluster, runs a query on the
sample data, and prints out the result.

Next Steps
----------

.. include:: /includes/quick-start/next-steps.rst
Loading
Loading