|
| 1 | +.. _golang-faq: |
| 2 | + |
| 3 | +=== |
| 4 | +FAQ |
| 5 | +=== |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, connection error, question, help |
| 13 | + :description: Find answers to common questions about the MongoDB Go Driver, including connection pooling, error handling, and BSON to JSON conversion. |
| 14 | + |
| 15 | +.. contents:: On this page |
| 16 | + :local: |
| 17 | + :backlinks: none |
| 18 | + :depth: 1 |
| 19 | + :class: singlecol |
| 20 | + |
| 21 | +This page contains frequently asked questions and their corresponding answers. |
| 22 | + |
| 23 | +.. tip:: |
| 24 | + |
| 25 | + If you can't find an answer to your problem on this page, |
| 26 | + see the :ref:`golang-issues-and-help` page for next steps and more |
| 27 | + resources. |
| 28 | + |
| 29 | +Why Am I Getting Errors While Connecting to MongoDB? |
| 30 | +---------------------------------------------------- |
| 31 | + |
| 32 | +If you have trouble connecting to a MongoDB deployment, see |
| 33 | +the :ref:`Connection Troubleshooting Guide <golang-connection-troubleshooting>` |
| 34 | +for possible solutions. |
| 35 | + |
| 36 | +.. _golang-faq-connection-pool: |
| 37 | + |
| 38 | +How Does Connection Pooling Work in the {+driver-short+}? |
| 39 | +--------------------------------------------------------- |
| 40 | + |
| 41 | +Every ``Client`` instance has a built-in connection pool for each server |
| 42 | +in your MongoDB topology. Connection pools open sockets on demand to support |
| 43 | +concurrent MongoDB operations, or `goroutines |
| 44 | +<https://www.golang-book.com/books/intro/10>`__, in your application. |
| 45 | + |
| 46 | +The maximum size of each connection pool is set by the ``maxPoolSize`` option, which |
| 47 | +defaults to ``100``. If the number of in-use connections to a server reaches |
| 48 | +the value of ``maxPoolSize``, the next request to that server will wait |
| 49 | +until a connection becomes available. |
| 50 | + |
| 51 | +The ``Client`` instance opens two additional sockets per server in your |
| 52 | +MongoDB topology for monitoring the server's state. |
| 53 | + |
| 54 | +For example, a client connected to a 3-node replica set opens 6 |
| 55 | +monitoring sockets. It also opens the necessary sockets to support |
| 56 | +an application's concurrent operations on each server, up to |
| 57 | +the value of ``maxPoolSize``. If ``maxPoolSize`` is ``100`` and the |
| 58 | +application only uses the primary (the default), then only the primary |
| 59 | +connection pool grows and there can be at most ``106`` total connections. If the |
| 60 | +application uses a :ref:`read preference <golang-read-pref>` to query the |
| 61 | +secondary nodes, their pools also grow and there can be ``306`` total connections. |
| 62 | + |
| 63 | +Additionally, connection pools are rate-limited such that each connection pool |
| 64 | +can only create, at maximum, the value of ``maxConnecting`` connections |
| 65 | +in parallel at any time. Any additional goroutine stops waiting in the |
| 66 | +following cases: |
| 67 | + |
| 68 | +- One of the existing goroutines finishes creating a connection, or |
| 69 | + an existing connection is checked back into the pool. |
| 70 | +- The driver's ability to reuse existing connections improves due to |
| 71 | + rate-limits on connection creation. |
| 72 | + |
| 73 | +You can set the minimum number of concurrent connections to |
| 74 | +each server by using the ``minPoolSize`` option, which defaults to ``0``. |
| 75 | +After setting ``minPoolSize``, the connection pool is initialized with |
| 76 | +this number of sockets. If sockets close due to any network errors, causing |
| 77 | +the total number of sockets (both in use and idle) to drop below the minimum, more sockets |
| 78 | +open until the minimum is reached. |
| 79 | + |
| 80 | +You can set the maximum number of milliseconds that a connection can |
| 81 | +remain idle in the pool before being removed and replaced with |
| 82 | +the ``maxIdleTimeMS`` option, which defaults to ``None`` (no limit). |
| 83 | + |
| 84 | +The following default configuration for a ``Client`` works for most applications: |
| 85 | + |
| 86 | +.. code-block:: go |
| 87 | + |
| 88 | + client, err := mongo.Connect(options.Client().ApplyURI("<connection string>")) |
| 89 | + |
| 90 | +Create a client once for each process, and reuse it for all |
| 91 | +operations. It is a common mistake to create a new client for each |
| 92 | +request, which is very inefficient. |
| 93 | + |
| 94 | +To support high numbers of concurrent MongoDB operations |
| 95 | +within one process, you can increase ``maxPoolSize``. Once the pool |
| 96 | +reaches its maximum size, additional operations wait for sockets |
| 97 | +to become available. |
| 98 | + |
| 99 | +The driver does not limit the number of operations that |
| 100 | +can wait for sockets to become available and it is the application's |
| 101 | +responsibility to limit the size of its pool to bound queuing |
| 102 | +during a load spike. Operations can wait for any length of time |
| 103 | +unless you define the ``waitQueueTimeoutMS`` option. |
| 104 | + |
| 105 | +An operation that waits more than the length of time defined by |
| 106 | +``waitQueueTimeoutMS`` for a socket raises a connection error. Use this |
| 107 | +option if it is more important to bound the duration of operations |
| 108 | +during a load spike than it is to complete every operation. |
| 109 | + |
| 110 | +When ``Client.Disconnect()`` is called by any goroutine, the driver |
| 111 | +closes all idle sockets and closes all sockets that are in |
| 112 | +use as they are returned to the pool. |
| 113 | + |
| 114 | +How Can I Fix the "WriteNull can only write while positioned on a Element or Value but is positioned on a TopLevel" Error? |
| 115 | +-------------------------------------------------------------------------------------------------------------------------- |
| 116 | + |
| 117 | +The ``bson.Marshal()`` method requires a parameter that can be decoded |
| 118 | +into a BSON document, such as the ``bson.D`` type. This error occurs |
| 119 | +when you pass something *other* than a BSON document to |
| 120 | +``bson.Marshal()``. |
| 121 | + |
| 122 | +The ``WriteNull`` error occurs when you pass a ``null`` to |
| 123 | +``bson.Marshal()``. Situations in which a similar error can occur |
| 124 | +include the following: |
| 125 | + |
| 126 | +- You pass a string to ``bson.Marshal()``, causing a ``WriteString`` error. |
| 127 | +- You pass a boolean to ``bson.Marshal()``, causing a ``WriteBoolean`` error. |
| 128 | +- You pass an integer to ``bson.Marshal()``, causing a ``WriteInt32`` error. |
| 129 | + |
| 130 | +You may encounter this error when you perform a CRUD operation that |
| 131 | +internally uses the ``bson.Marshal()`` method or when you call |
| 132 | +``bson.Marshal()`` directly to encode data. |
| 133 | + |
| 134 | +The following code produces a ``WriteNull`` error because the driver |
| 135 | +cannot encode the ``null`` value of ``sortOrder`` to BSON during |
| 136 | +the ``FindOneAndUpdate()`` operation: |
| 137 | + |
| 138 | +.. code-block:: go |
| 139 | + |
| 140 | + var sortOrder bson.D |
| 141 | + opts := options.FindOneAndUpdate().SetSort(sortOrder) |
| 142 | + |
| 143 | + updateDocument := bson.D{{"$inc", bson.D{{"counter", 1}}}} |
| 144 | + result := coll.FindOneAndUpdate(context.TODO(), bson.D{}, updateDocument, opts) |
| 145 | + if err := result.Err(); err != nil { |
| 146 | + panic(err) |
| 147 | + } |
| 148 | + |
| 149 | +The following code shows how to correctly initialize the ``sortOrder`` |
| 150 | +variable as a ``bson.D`` type so that the driver can convert it to BSON: |
| 151 | + |
| 152 | +.. code-block:: go |
| 153 | + |
| 154 | + sortOrder := bson.D{} |
| 155 | + |
| 156 | +How Do I Convert a BSON Document to JSON? |
| 157 | +----------------------------------------- |
| 158 | + |
| 159 | +The driver provides a variety of marshaler methods that can be used to |
| 160 | +convert a BSON document to JSON, such as the ``MarshalExtJSON()`` |
| 161 | +method. To view a readable form of the JSON encoding, you must use |
| 162 | +an unmarshaler method or string type-casting to parse the JSON byte |
| 163 | +format. |
| 164 | + |
| 165 | +The following code converts a BSON document to JSON using the |
| 166 | +``MarshalExtJSON()`` method, then parses and prints the JSON byte array |
| 167 | +using string type-casting: |
| 168 | + |
| 169 | +.. io-code-block:: |
| 170 | + :copyable: true |
| 171 | + |
| 172 | + .. input:: |
| 173 | + :language: go |
| 174 | + :emphasize-lines: 3 |
| 175 | + |
| 176 | + bsonDocument := bson.D{{"hello", "world"}} |
| 177 | + |
| 178 | + jsonBytes, err := bson.MarshalExtJSON(bsonDocument, true, false) |
| 179 | + if err != nil { |
| 180 | + panic(err) |
| 181 | + } |
| 182 | + |
| 183 | + fmt.Println(string(jsonBytes)) |
| 184 | + |
| 185 | + .. output:: |
| 186 | + :language: none |
| 187 | + :visible: false |
| 188 | + |
| 189 | + {"hello":"world"} |
| 190 | + |
| 191 | +To learn more about conversions between BSON and Go types, see the |
| 192 | +:ref:`golang-bson` guide. |
0 commit comments