Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
1124133
DOCSP-47019 Shift Go ToC (#499)
lindseymoore May 19, 2025
27469a6
DOCSP-47018 Authentication Reorg (#502)
lindseymoore May 29, 2025
ef26268
DOCSP-49975 Specify Documents to Return (#503)
lindseymoore Jun 2, 2025
f44f352
DOCSP-47020 Databases and collections (#504)
stephmarie17 Jun 4, 2025
13fdcc3
DOCSP-49977 Replace One (#506)
lindseymoore Jun 6, 2025
c7bb8c1
DOCSP-47023 Connection pools (#505)
stephmarie17 Jun 6, 2025
328df75
DOCSP-49972 removing extra files
mballard-mdb Jun 9, 2025
71da778
DOCSP-49972 Suggestions from review
mballard-mdb Jun 9, 2025
20a14f5
DOCS-49972 nits
mballard-mdb Jun 9, 2025
beb8820
Merge Go Connection Target PR
mballard-mdb Jun 11, 2025
cde5481
DOCSP-47022 Add link to replication manual (#519)
stephmarie17 Jun 13, 2025
35c6def
DOCSP-47006 Retryable Writes and Reads (#518)
stephmarie17 Jun 13, 2025
a1e8e81
DOCSP-49973 Create a MongoClient (#507)
stephmarie17 Jun 13, 2025
7a8c432
DOCSP-49986: TLS (#520)
rustagir Jun 17, 2025
3c5ac37
DOCSP-50749: agg tutorial link (#521)
rustagir Jun 17, 2025
28bd586
DOCSP-49622 Atlas Search (#508)
lindseymoore Jun 17, 2025
8178d41
DOCSP-49976 Update Documents (#517)
lindseymoore Jun 26, 2025
98a7ca5
DOCSP-49982 Monitor Application Events (#525)
lindseymoore Jun 30, 2025
0c05c2c
DOCSP-50493: quick reference cleanup (#527)
rustagir Jul 2, 2025
8cac163
DOCSP-49621 Customize cluster settings (#522)
stephmarie17 Jul 2, 2025
8b35c0b
DOCSP-47011: Extended JSON (#528)
rustagir Jul 3, 2025
861396c
DOCSP-51236: Remove support for MONGODB-CR auth
mcmorisi Jul 7, 2025
280f8e5
Fix
mcmorisi Jul 7, 2025
940d4e1
Merge pull request #529 from mcmorisi/DOCSP-51236-remove-cr-auth
mcmorisi Jul 7, 2025
bac1552
DOCSP-49971: csot cc (#526)
rustagir Jul 7, 2025
00af4ee
add upgrade guide and ref links
stephmarie17 Jul 7, 2025
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
11 changes: 8 additions & 3 deletions snooty.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
name = "golang"
title = "Go Driver"
toc_landing_pages = [
"/fundamentals/connections",
"/fundamentals/crud",
"/usage-examples",
"/connect",
"/crud",
"/crud/update",
"/monitoring-and-logging",
"/security",
"/security/authentication",
"/connect/specify-connection-options",
]

intersphinx = [
Expand All @@ -17,6 +21,7 @@ sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/"
api-version = "v2"
driver-long = "MongoDB Go Driver"
driver-short = "Go driver"
language = "Go"
docs-branch = "master"
version = "v2.1"
full-version = "{+version+}.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ pipeline consists of one or more **stages**. Each stage performs an
operation based on its expression operators. After the driver executes
the aggregation pipeline, it returns an aggregated result.

.. sharedinclude:: dbx/agg-tutorials-manual-tip.rst

.. replacement:: language

:guilabel:`{+language+}`

Analogy
~~~~~~~

Expand Down
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
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
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
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.
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
.. _golang-watch-changes:
.. _golang-monitor-changes:

====================
Monitor Data Changes
====================
Expand Down
Loading
Loading