diff --git a/snooty.toml b/snooty.toml index 7e83afef..ee08024d 100644 --- a/snooty.toml +++ b/snooty.toml @@ -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 = [ diff --git a/source/fundamentals/aggregation.txt b/source/aggregation.txt similarity index 100% rename from source/fundamentals/aggregation.txt rename to source/aggregation.txt diff --git a/source/archive-reference-files/faq.txt b/source/archive-reference-files/faq.txt new file mode 100644 index 00000000..c38a73e8 --- /dev/null +++ b/source/archive-reference-files/faq.txt @@ -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 ` +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 +`__, 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 ` 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("")) + +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. diff --git a/source/fundamentals.txt b/source/archive-reference-files/fundamentals.txt similarity index 100% rename from source/fundamentals.txt rename to source/archive-reference-files/fundamentals.txt diff --git a/source/fundamentals/auth.txt b/source/archive-reference-files/fundamentals/auth.txt similarity index 100% rename from source/fundamentals/auth.txt rename to source/archive-reference-files/fundamentals/auth.txt diff --git a/source/fundamentals/collations.txt b/source/archive-reference-files/fundamentals/collations.txt similarity index 100% rename from source/fundamentals/collations.txt rename to source/archive-reference-files/fundamentals/collations.txt diff --git a/source/fundamentals/connections/connection-guide.txt b/source/archive-reference-files/fundamentals/connections/connection-guide.txt similarity index 100% rename from source/fundamentals/connections/connection-guide.txt rename to source/archive-reference-files/fundamentals/connections/connection-guide.txt diff --git a/source/fundamentals/connections/tls.txt b/source/archive-reference-files/fundamentals/connections/tls.txt similarity index 100% rename from source/fundamentals/connections/tls.txt rename to source/archive-reference-files/fundamentals/connections/tls.txt diff --git a/source/fundamentals/context.txt b/source/archive-reference-files/fundamentals/context.txt similarity index 100% rename from source/fundamentals/context.txt rename to source/archive-reference-files/fundamentals/context.txt diff --git a/source/fundamentals/crud/read-operations.txt b/source/archive-reference-files/fundamentals/crud/read-operations.txt similarity index 100% rename from source/fundamentals/crud/read-operations.txt rename to source/archive-reference-files/fundamentals/crud/read-operations.txt diff --git a/source/fundamentals/crud/read-operations/changestream.txt b/source/archive-reference-files/fundamentals/crud/read-operations/changestream.txt similarity index 100% rename from source/fundamentals/crud/read-operations/changestream.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/changestream.txt diff --git a/source/fundamentals/crud/read-operations/count.txt b/source/archive-reference-files/fundamentals/crud/read-operations/count.txt similarity index 100% rename from source/fundamentals/crud/read-operations/count.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/count.txt diff --git a/source/fundamentals/crud/read-operations/limit.txt b/source/archive-reference-files/fundamentals/crud/read-operations/limit.txt similarity index 100% rename from source/fundamentals/crud/read-operations/limit.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/limit.txt diff --git a/source/fundamentals/crud/read-operations/skip.txt b/source/archive-reference-files/fundamentals/crud/read-operations/skip.txt similarity index 100% rename from source/fundamentals/crud/read-operations/skip.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/skip.txt diff --git a/source/fundamentals/crud/read-operations/sort.txt b/source/archive-reference-files/fundamentals/crud/read-operations/sort.txt similarity index 100% rename from source/fundamentals/crud/read-operations/sort.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/sort.txt diff --git a/source/fundamentals/crud/read-operations/text.txt b/source/archive-reference-files/fundamentals/crud/read-operations/text.txt similarity index 100% rename from source/fundamentals/crud/read-operations/text.txt rename to source/archive-reference-files/fundamentals/crud/read-operations/text.txt diff --git a/source/fundamentals/crud/write-operations.txt b/source/archive-reference-files/fundamentals/crud/write-operations.txt similarity index 100% rename from source/fundamentals/crud/write-operations.txt rename to source/archive-reference-files/fundamentals/crud/write-operations.txt diff --git a/source/fundamentals/crud/write-read-pref.txt b/source/archive-reference-files/fundamentals/crud/write-read-pref.txt similarity index 100% rename from source/fundamentals/crud/write-read-pref.txt rename to source/archive-reference-files/fundamentals/crud/write-read-pref.txt diff --git a/source/fundamentals/enterprise-auth.txt b/source/archive-reference-files/fundamentals/enterprise-auth.txt similarity index 100% rename from source/fundamentals/enterprise-auth.txt rename to source/archive-reference-files/fundamentals/enterprise-auth.txt diff --git a/source/fundamentals/monitoring.txt b/source/archive-reference-files/fundamentals/monitoring.txt similarity index 100% rename from source/fundamentals/monitoring.txt rename to source/archive-reference-files/fundamentals/monitoring.txt diff --git a/source/fundamentals/monitoring/cluster-monitoring.txt b/source/archive-reference-files/fundamentals/monitoring/cluster-monitoring.txt similarity index 100% rename from source/fundamentals/monitoring/cluster-monitoring.txt rename to source/archive-reference-files/fundamentals/monitoring/cluster-monitoring.txt diff --git a/source/fundamentals/monitoring/command-monitoring.txt b/source/archive-reference-files/fundamentals/monitoring/command-monitoring.txt similarity index 100% rename from source/fundamentals/monitoring/command-monitoring.txt rename to source/archive-reference-files/fundamentals/monitoring/command-monitoring.txt diff --git a/source/fundamentals/monitoring/connection-monitoring.txt b/source/archive-reference-files/fundamentals/monitoring/connection-monitoring.txt similarity index 100% rename from source/fundamentals/monitoring/connection-monitoring.txt rename to source/archive-reference-files/fundamentals/monitoring/connection-monitoring.txt diff --git a/source/fundamentals/time-series.txt b/source/archive-reference-files/fundamentals/time-series.txt similarity index 100% rename from source/fundamentals/time-series.txt rename to source/archive-reference-files/fundamentals/time-series.txt diff --git a/source/archive-reference-files/issues-and-help.txt b/source/archive-reference-files/issues-and-help.txt new file mode 100644 index 00000000..39902616 --- /dev/null +++ b/source/archive-reference-files/issues-and-help.txt @@ -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. + +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 `_. + +To learn more, refer to our `support channels `_. + +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 `_. +* Navigate to `the GODRIVER project `_. +* 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**. + +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 `. + +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 +`__ to +ensure your code passes any newly added and existing tests. diff --git a/source/archive-reference-files/quick-start.txt b/source/archive-reference-files/quick-start.txt new file mode 100644 index 00000000..c09e609b --- /dev/null +++ b/source/archive-reference-files/quick-start.txt @@ -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='' + + .. note:: + + Make sure to replace the ```` 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 ` 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 diff --git a/source/archive-reference-files/usage-examples.txt b/source/archive-reference-files/usage-examples.txt new file mode 100644 index 00000000..a1a82df0 --- /dev/null +++ b/source/archive-reference-files/usage-examples.txt @@ -0,0 +1,113 @@ +.. _golang-usage-examples: + +============== +Usage Examples +============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, write, example, code example + :description: Explore Go usage examples for common MongoDB operations, including finding, inserting, updating, and deleting documents, as well as monitoring data changes. + +.. toctree:: + + Find Operations + Write Operations + Bulk Operations + Open a Change Stream + Count Documents Method + Distinct Field Values + Run a Command + Use Struct Tags + +Overview +-------- + +Usage examples provide convenient starting points for popular MongoDB +operations. Each example provides the following: + +- A full Go program that you can run in your own environment +- The expected result after running the program + +How to Use the Usage Examples +----------------------------- + +These examples use the :atlas:`sample datasets ` provided by +Atlas. You can load them into your database on the free tier of MongoDB +Atlas by following the :atlas:`Get Started with Atlas Guide +` or you can +:guides:`import the sample dataset into a local MongoDB instance +`. + +Once you import the dataset, you can copy and paste a usage +example into your development environment of choice. You can follow the +:ref:`Quick Start ` to learn more about getting +started with the {+driver-long+}. + +Connection String +~~~~~~~~~~~~~~~~~ + +Follow the :ref:`"Connect to your Cluster" ` +step to find the +:manual:`connection string ` to define your +``MONGODB_URI`` environment variable to run the usage examples. If your +instance uses :manual:`SCRAM authentication `, +you can replace ```` with your database username, ```` with your +database password, and ```` with the URL or IP address of your instance. + +To learn more about connecting to your MongoDB instance, see :ref:`golang-connection-guide`. + +Environment Variable +~~~~~~~~~~~~~~~~~~~~ + +To connect the example to your MongoDB instance, you must :ref:`define +an environment variable ` by using +your connection string. + +.. code-block:: go + + uri := os.Getenv("MONGODB_URI") + +.. _golang-usage-examples-env-variable: + +You can use `GoDotEnv `__ to define +your environment variable. + +Add the following application configuration in your ``.env`` file at the +root of your project, replacing the placeholders with the values for your +deployment's connection string. To learn more, see the +`GoDotEnv documentation `__. + +.. code-block:: + + MONGODB_URI=mongodb+srv://:@?retryWrites=true&w=majority + +Examples +-------- + +You can find usage examples for the following tasks: + +- :ref:`golang-find-one` +- :ref:`golang-find-multiple` +- :ref:`golang-insert-one` +- :ref:`golang-insert-many` +- :ref:`golang-update-one` +- :ref:`golang-update-many` +- :ref:`golang-replace` +- :ref:`golang-delete-one` +- :ref:`golang-delete-many` +- :ref:`golang-bulk-ops-usage-example` +- :ref:`golang-watch` +- :ref:`golang-count-usage-example` +- :ref:`golang-distinct-usage-example` +- :ref:`golang-run-command-usage-example` +- :ref:`golang-struct-tags-usage-example` diff --git a/source/usage-examples/bulkWrite.txt b/source/archive-reference-files/usage-examples/bulkWrite.txt similarity index 100% rename from source/usage-examples/bulkWrite.txt rename to source/archive-reference-files/usage-examples/bulkWrite.txt diff --git a/source/usage-examples/changestream.txt b/source/archive-reference-files/usage-examples/changestream.txt similarity index 100% rename from source/usage-examples/changestream.txt rename to source/archive-reference-files/usage-examples/changestream.txt diff --git a/source/usage-examples/command.txt b/source/archive-reference-files/usage-examples/command.txt similarity index 100% rename from source/usage-examples/command.txt rename to source/archive-reference-files/usage-examples/command.txt diff --git a/source/usage-examples/count.txt b/source/archive-reference-files/usage-examples/count.txt similarity index 100% rename from source/usage-examples/count.txt rename to source/archive-reference-files/usage-examples/count.txt diff --git a/source/usage-examples/deleteMany.txt b/source/archive-reference-files/usage-examples/deleteMany.txt similarity index 100% rename from source/usage-examples/deleteMany.txt rename to source/archive-reference-files/usage-examples/deleteMany.txt diff --git a/source/usage-examples/deleteOne.txt b/source/archive-reference-files/usage-examples/deleteOne.txt similarity index 100% rename from source/usage-examples/deleteOne.txt rename to source/archive-reference-files/usage-examples/deleteOne.txt diff --git a/source/usage-examples/distinct.txt b/source/archive-reference-files/usage-examples/distinct.txt similarity index 100% rename from source/usage-examples/distinct.txt rename to source/archive-reference-files/usage-examples/distinct.txt diff --git a/source/usage-examples/facets.toml b/source/archive-reference-files/usage-examples/facets.toml similarity index 100% rename from source/usage-examples/facets.toml rename to source/archive-reference-files/usage-examples/facets.toml diff --git a/source/usage-examples/find-operations.txt b/source/archive-reference-files/usage-examples/find-operations.txt similarity index 100% rename from source/usage-examples/find-operations.txt rename to source/archive-reference-files/usage-examples/find-operations.txt diff --git a/source/usage-examples/find.txt b/source/archive-reference-files/usage-examples/find.txt similarity index 100% rename from source/usage-examples/find.txt rename to source/archive-reference-files/usage-examples/find.txt diff --git a/source/usage-examples/findOne.txt b/source/archive-reference-files/usage-examples/findOne.txt similarity index 100% rename from source/usage-examples/findOne.txt rename to source/archive-reference-files/usage-examples/findOne.txt diff --git a/source/usage-examples/insertMany.txt b/source/archive-reference-files/usage-examples/insertMany.txt similarity index 100% rename from source/usage-examples/insertMany.txt rename to source/archive-reference-files/usage-examples/insertMany.txt diff --git a/source/usage-examples/insertOne.txt b/source/archive-reference-files/usage-examples/insertOne.txt similarity index 100% rename from source/usage-examples/insertOne.txt rename to source/archive-reference-files/usage-examples/insertOne.txt diff --git a/source/usage-examples/replaceOne.txt b/source/archive-reference-files/usage-examples/replaceOne.txt similarity index 100% rename from source/usage-examples/replaceOne.txt rename to source/archive-reference-files/usage-examples/replaceOne.txt diff --git a/source/usage-examples/struct-tagging.txt b/source/archive-reference-files/usage-examples/struct-tagging.txt similarity index 100% rename from source/usage-examples/struct-tagging.txt rename to source/archive-reference-files/usage-examples/struct-tagging.txt diff --git a/source/usage-examples/updateMany.txt b/source/archive-reference-files/usage-examples/updateMany.txt similarity index 100% rename from source/usage-examples/updateMany.txt rename to source/archive-reference-files/usage-examples/updateMany.txt diff --git a/source/usage-examples/updateOne.txt b/source/archive-reference-files/usage-examples/updateOne.txt similarity index 100% rename from source/usage-examples/updateOne.txt rename to source/archive-reference-files/usage-examples/updateOne.txt diff --git a/source/usage-examples/write-operations.txt b/source/archive-reference-files/usage-examples/write-operations.txt similarity index 100% rename from source/usage-examples/write-operations.txt rename to source/archive-reference-files/usage-examples/write-operations.txt diff --git a/source/atlas-search.txt b/source/atlas-search.txt new file mode 100644 index 00000000..b099a5bd --- /dev/null +++ b/source/atlas-search.txt @@ -0,0 +1,8 @@ +.. _golang-atlas-search: + +========================= +Run an Atlas Search Query +========================= + +.. TODO + diff --git a/source/fundamentals/atlas-vector-search.txt b/source/atlas-vector-search.txt similarity index 100% rename from source/fundamentals/atlas-vector-search.txt rename to source/atlas-vector-search.txt diff --git a/source/connect.txt b/source/connect.txt new file mode 100644 index 00000000..61cd063a --- /dev/null +++ b/source/connect.txt @@ -0,0 +1,36 @@ +.. _go-connect: +.. _golang-connection: + +================== +Connect to MongoDB +================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. meta:: + :description: Learn how to use {+driver-short+} to connect to MongoDB. + :keywords: client, ssl + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Create a MongoClient + Choose a Connection Target + Connection Options + Connection Troubleshooting + +Overview +-------- + +Learn how to use the {+driver-short+} to configure your application's +connection to a MongoDB deployment in the following sections: + +- :ref:`golang-connection-guide` +- :ref:`golang-connection-options` +- :ref:`golang-network-compression` +- :ref:`golang-connection-troubleshooting` diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt new file mode 100644 index 00000000..0ab8d363 --- /dev/null +++ b/source/connect/connection-options.txt @@ -0,0 +1,14 @@ +================== +Connection Options +================== + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Specify Connection Options + Compress Network Traffic + Customize Server Selection + Stable API + Limit Server Execution Time + Connection Pools diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt new file mode 100644 index 00000000..f6d55bcc --- /dev/null +++ b/source/connect/connection-options/connection-pools.txt @@ -0,0 +1,6 @@ + +================ +Connection Pools +================ + +.. TODO \ No newline at end of file diff --git a/source/connect/connection-options/csot.txt b/source/connect/connection-options/csot.txt new file mode 100644 index 00000000..bb90e174 --- /dev/null +++ b/source/connect/connection-options/csot.txt @@ -0,0 +1,6 @@ + +=========================== +Limit Server Execution Time +=========================== + +.. TODO \ No newline at end of file diff --git a/source/fundamentals/connections/network-compression.txt b/source/connect/connection-options/network-compression.txt similarity index 100% rename from source/fundamentals/connections/network-compression.txt rename to source/connect/connection-options/network-compression.txt diff --git a/source/connect/connection-options/server-selection.txt b/source/connect/connection-options/server-selection.txt new file mode 100644 index 00000000..ac55fa3e --- /dev/null +++ b/source/connect/connection-options/server-selection.txt @@ -0,0 +1 @@ +.. TODO \ No newline at end of file diff --git a/source/fundamentals/connections/connection-options.txt b/source/connect/connection-options/specify-connection-options.txt similarity index 98% rename from source/fundamentals/connections/connection-options.txt rename to source/connect/connection-options/specify-connection-options.txt index af2537da..569a671a 100644 --- a/source/fundamentals/connections/connection-options.txt +++ b/source/connect/connection-options/specify-connection-options.txt @@ -1,8 +1,8 @@ .. _golang-connection-options: -================== -Connection Options -================== +========================== +Specify Connection Options +========================== .. facet:: :name: genre diff --git a/source/fundamentals/stable-api.txt b/source/connect/connection-options/stable-api.txt similarity index 100% rename from source/fundamentals/stable-api.txt rename to source/connect/connection-options/stable-api.txt diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt new file mode 100644 index 00000000..88c5ae10 --- /dev/null +++ b/source/connect/connection-targets.txt @@ -0,0 +1,16 @@ +.. _golang-connection-targets: + +========================== +Choose a Connection Target +========================== + +.. meta:: + :keywords: connection string, URI, server, settings, client, load balancing, srv, dns + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. TODO \ No newline at end of file diff --git a/source/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt similarity index 100% rename from source/connection-troubleshooting.txt rename to source/connect/connection-troubleshooting.txt diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt new file mode 100644 index 00000000..226818c7 --- /dev/null +++ b/source/connect/mongoclient.txt @@ -0,0 +1,14 @@ +.. _golang-mongoclient: + +==================== +Create a MongoClient +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + + +.. TODO \ No newline at end of file diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 00000000..e9badd30 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,34 @@ +.. _golang-crud: + +=============== +CRUD Operations +=============== + +.. meta:: + :description: Explore how to perform CRUD operations using the MongoDB Go Driver, including creating, reading, updating, and deleting documents. + +.. toctree:: + :caption: CRUD Operations + + Insert Documents + Query Documents + Update Documents + Delete Documents + Bulk Write Operations + Transactions + Compound Operations + Configure CRUD Operations + Store Large Files + +CRUD (Create, Read, Update, Delete) operations enable you to work with +data stored in MongoDB. + +- :ref:`golang-insert-guide` +- :ref:`golang-query` +- :ref:`golang-update` +- :ref:`golang-delete` +- :ref:`golang-bulk` +- :ref:`golang-compound-operations` +- :ref:`golang-transactions` +- :ref:`golang-configure-crud` +- :ref:`golang-gridfs` diff --git a/source/fundamentals/crud/write-operations/bulk.txt b/source/crud/bulk.txt similarity index 100% rename from source/fundamentals/crud/write-operations/bulk.txt rename to source/crud/bulk.txt diff --git a/source/fundamentals/crud/compound-operations.txt b/source/crud/compound-operations.txt similarity index 100% rename from source/fundamentals/crud/compound-operations.txt rename to source/crud/compound-operations.txt diff --git a/source/crud/configure.txt b/source/crud/configure.txt new file mode 100644 index 00000000..398b62d4 --- /dev/null +++ b/source/crud/configure.txt @@ -0,0 +1,21 @@ +.. _golang-configure-crud: + +========================= +Configure CRUD Operations +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: insert, update, replace, delete, options, code example + +.. TODO + diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/crud/delete.txt similarity index 99% rename from source/fundamentals/crud/write-operations/delete.txt rename to source/crud/delete.txt index 2d075d50..aeaecefd 100644 --- a/source/fundamentals/crud/write-operations/delete.txt +++ b/source/crud/delete.txt @@ -1,4 +1,5 @@ .. _golang-delete-guide: +.. _golang-delete: ================ Delete Documents diff --git a/source/fundamentals/gridfs.txt b/source/crud/gridfs.txt similarity index 100% rename from source/fundamentals/gridfs.txt rename to source/crud/gridfs.txt diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/crud/insert.txt similarity index 100% rename from source/fundamentals/crud/write-operations/insert.txt rename to source/crud/insert.txt diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 00000000..9d66f020 --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,16 @@ +================ +Query Operations +================ + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Specify a Query + Find Documents + Specify Documents to Return + Specify Fields to Return + Count Documents + Distinct Field Values + Access Data from a Cursor + Geospatial Queries diff --git a/source/crud/query/count.txt b/source/crud/query/count.txt new file mode 100644 index 00000000..6c1ce856 --- /dev/null +++ b/source/crud/query/count.txt @@ -0,0 +1,261 @@ +.. _golang-count-documents: + +=============== +Count Documents +=============== + +.. meta:: + :description: Learn to count documents in a MongoDB collection using Go, including accurate, estimated, and aggregation-based methods. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to get an :ref:`accurate +` and :ref:`estimated ` count of +the number of documents in your collection. + +Sample Data +~~~~~~~~~~~ + +The examples in this section use the following ``Tea`` struct as a model for documents +in the ``tea`` collection: + +.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go + :start-after: start-tea-struct + :end-before: end-tea-struct + :language: go + :dedent: + +To run the examples in this guide, load the sample data into the ``tea`` collection in the ``db`` +database with the following snippet: + +.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go + :language: go + :dedent: + :start-after: begin insert docs + :end-before: end insert docs + +.. include:: /includes/fundamentals/automatic-db-coll-creation.rst + +Each document describes a tea type and its rating. These items +correspond to the ``type`` and ``rating`` fields. + +.. _golang-accurate-count: + +Accurate Count +-------------- + +To count the number of documents that match your query filter, use the +``CountDocuments()`` method. If you pass an empty query filter, this method +returns the total number of documents in the collection. + +.. tip:: + + When you use ``CountDocuments()`` to return the total number of documents in a + collection, MongoDB performs a collection scan. You can avoid a collection scan and + improve the performance of this method by using a :manual:`hint + ` to take advantage of the built-in index on + the ``_id`` field. Use this technique only when calling ``CountDocuments()`` + with an empty query parameter. + + .. code-block:: go + :emphasize-lines: 1, 3 + + opts := options.Count().SetHint("_id_") + + count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts) + if err != nil { + panic(err) + } + +Modify Behavior +~~~~~~~~~~~~~~~ + +You can modify the behavior of ``CountDocuments()`` by passing in a +``CountOptions`` type. If you don't specify any options, the driver uses +its default values. + +The ``CountOptions`` type allows you to configure options with the +following methods: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``SetCollation()`` + - | The type of language collation to use when sorting results. + | Default: ``nil`` + + * - ``SetHint()`` + - | The index to use to scan for documents to count. + | Default: ``nil`` + + * - ``SetLimit()`` + - | The maximum number of documents to count. + | Default: ``0`` + + * - ``SetSkip()`` + - | The number of documents to skip before counting. + | Default: ``0`` + +Example +``````` + +The following example counts the number of documents where the +``rating`` is less than ``6``: + +.. io-code-block:: + :copyable: true + + .. input:: + :language: go + + filter := bson.D{{"rating", bson.D{{"$lt", 6}}}} + + count, err := coll.CountDocuments(context.TODO(), filter) + if err != nil { + panic(err) + } + fmt.Printf("Number of documents with a rating less than six: %d\n", count) + + .. output:: + :language: none + :visible: false + + Number of documents with a rating less than six: 4 + +.. _golang-count-aggregation: + +Aggregation +----------- + +You can also include the :manual:`$count ` +stage to count the number of documents in an aggregation pipeline. + +Example +~~~~~~~ + +The following example performs the following actions: + +- Counts the number of documents in which the value of the ``rating`` field is greater + than ``5`` +- Assigns the count to the ``counted_documents`` field + +.. io-code-block:: + :copyable: true + + .. input:: + :language: go + + matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}} + countStage := bson.D{{"$count", "counted_documents"}} + + cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, countStage}) + if err != nil { + panic(err) + } + + var results []bson.D + if err = cursor.All(context.TODO(), &results); err != nil { + panic(err) + } + for _, result := range results { + fmt.Println(result) + } + + .. output:: + :language: none + :visible: false + + [{counted_documents 5}] + +.. _golang-estimated-count: + +Estimated Count +--------------- + +To estimate the number of documents in your collection, use the +``EstimatedDocumentCount()`` method. + +.. note:: + + The ``EstimatedDocumentCount()`` method is quicker than the + ``CountDocuments()`` method because it uses the collection's + metadata rather than scanning the entire collection. + +Modify Behavior +~~~~~~~~~~~~~~~ + +You can modify the behavior of ``EstimatedDocumentCount()`` by passing +in an ``EstimatedDocumentCountOptions`` type. If you don't specify any +options, the driver uses its default values. + +The ``EstimatedDocumentCountOptions`` type allows you to configure +options by using the following methods: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``SetComment()`` + - | Sets a comment to attach to the count operation. + | Default: ``nil`` + +Example +``````` + +The following example estimates the number of documents in the +``tea`` collection: + +.. io-code-block:: + :copyable: true + + .. input:: + :language: go + + count, err := coll.EstimatedDocumentCount(context.TODO()) + if err != nil { + panic(err) + } + fmt.Printf("Estimated number of documents in the tea collection: %d\n", count) + + .. output:: + :language: none + :visible: false + + Estimated number of documents in the tea collection: 9 + +Additional Information +---------------------- + +To learn more about the operations mentioned, see the following +guides: + +- :ref:`golang-query-document` +- :ref:`golang-skip` +- :ref:`golang-limit` +- :ref:`golang-aggregation` +- :ref:`golang-collations` + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API Documentation: + +- `CountDocuments() <{+api+}/mongo#Collection.CountDocuments>`__ +- `CountOptions <{+api+}/mongo/options#CountOptions>`__ +- `EstimatedDocumentCount() <{+api+}/mongo#Collection.EstimatedDocumentCount>`__ +- `EstimatedDocumentCountOptions <{+api+}/mongo/options#EstimatedDocumentCountOptions>`__ diff --git a/source/fundamentals/crud/read-operations/cursor.txt b/source/crud/query/cursor.txt similarity index 100% rename from source/fundamentals/crud/read-operations/cursor.txt rename to source/crud/query/cursor.txt diff --git a/source/fundamentals/crud/read-operations/distinct.txt b/source/crud/query/distinct.txt similarity index 100% rename from source/fundamentals/crud/read-operations/distinct.txt rename to source/crud/query/distinct.txt diff --git a/source/fundamentals/geo.txt b/source/crud/query/geo.txt similarity index 100% rename from source/fundamentals/geo.txt rename to source/crud/query/geo.txt diff --git a/source/fundamentals/crud/read-operations/project.txt b/source/crud/query/project.txt similarity index 100% rename from source/fundamentals/crud/read-operations/project.txt rename to source/crud/query/project.txt diff --git a/source/fundamentals/crud/read-operations/query-document.txt b/source/crud/query/query-document.txt similarity index 99% rename from source/fundamentals/crud/read-operations/query-document.txt rename to source/crud/query/query-document.txt index 18c3bac0..ad0f684f 100644 --- a/source/fundamentals/crud/read-operations/query-document.txt +++ b/source/crud/query/query-document.txt @@ -1,4 +1,6 @@ .. _golang-query-document: +.. _golang-query: +.. _golang-crud-read-operations: =============== Specify a Query diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/crud/query/retrieve.txt similarity index 99% rename from source/fundamentals/crud/read-operations/retrieve.txt rename to source/crud/query/retrieve.txt index 48fc0d30..4087759c 100644 --- a/source/fundamentals/crud/read-operations/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -1,7 +1,7 @@ .. _golang-retrieve: ============== -Retrieve Data +Find Documents ============== .. meta:: diff --git a/source/crud/query/specify-return-documents.txt b/source/crud/query/specify-return-documents.txt new file mode 100644 index 00000000..b162714a --- /dev/null +++ b/source/crud/query/specify-return-documents.txt @@ -0,0 +1,20 @@ +.. _golang-specify-documents-to-return: + +=========================== +Specify Documents to Return +=========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, paginate, pagination, order, code example + +.. TODO \ No newline at end of file diff --git a/source/fundamentals/transactions.txt b/source/crud/transactions.txt similarity index 100% rename from source/fundamentals/transactions.txt rename to source/crud/transactions.txt diff --git a/source/fundamentals/crud/write-operations/modify.txt b/source/crud/update.txt similarity index 99% rename from source/fundamentals/crud/write-operations/modify.txt rename to source/crud/update.txt index 6f021206..bbbb7777 100644 --- a/source/fundamentals/crud/write-operations/modify.txt +++ b/source/crud/update.txt @@ -1,4 +1,5 @@ .. _golang-change-document: +.. _golang-update: ================ Modify Documents @@ -18,6 +19,8 @@ Modify Documents :depth: 2 :class: singlecol +.. TODO edit + Overview -------- diff --git a/source/fundamentals/crud/write-operations/embedded-arrays.txt b/source/crud/update/embedded-arrays.txt similarity index 100% rename from source/fundamentals/crud/write-operations/embedded-arrays.txt rename to source/crud/update/embedded-arrays.txt diff --git a/source/crud/update/replace.txt b/source/crud/update/replace.txt new file mode 100644 index 00000000..c2a43651 --- /dev/null +++ b/source/crud/update/replace.txt @@ -0,0 +1,18 @@ +================= +Replace Documents +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, go, write, add data, change + +.. TODO \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/upsert.txt b/source/crud/update/upsert.txt similarity index 100% rename from source/fundamentals/crud/write-operations/upsert.txt rename to source/crud/update/upsert.txt diff --git a/source/data-formats.txt b/source/data-formats.txt new file mode 100644 index 00000000..d34d40ff --- /dev/null +++ b/source/data-formats.txt @@ -0,0 +1,26 @@ +.. _node-data-formats: + +======================== +Specialized Data Formats +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: bson, uuid, date, time + +.. TODO Landing page + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + BSON diff --git a/source/fundamentals/bson.txt b/source/data-formats/bson.txt similarity index 100% rename from source/fundamentals/bson.txt rename to source/data-formats/bson.txt diff --git a/source/databases-collections.txt b/source/databases-collections.txt new file mode 100644 index 00000000..fc96f0ca --- /dev/null +++ b/source/databases-collections.txt @@ -0,0 +1,7 @@ +.. _golang-databases-collections: + +========================= +Databases and Collections +========================= + +.. TODO \ No newline at end of file diff --git a/source/fundamentals/connections.txt b/source/fundamentals/connections.txt deleted file mode 100644 index 7bb9145e..00000000 --- a/source/fundamentals/connections.txt +++ /dev/null @@ -1,39 +0,0 @@ -.. _golang-connection: - -=========== -Connections -=========== - -.. meta:: - :description: Explore how to configure connections to a MongoDB deployment using the MongoDB Go Driver, including options for TLS and network compression. - -.. toctree:: - - Connection Guide - Connection Options - Network Compression - Configure TLS - Connect with AWS Lambda - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -Learn how to use the {+driver-short+} to configure your application's -connection to a MongoDB deployment in the following sections: - -- :ref:`golang-connection-guide` -- :ref:`golang-connection-options` -- :ref:`golang-network-compression` -- :ref:`golang-tls` -- :atlas:`Connect to MongoDB Atlas from AWS Lambda ` - -To learn how to authenticate to MongoDB, see the following pages: - -- :ref:`golang-authentication-mechanisms` -- :ref:`golang-enterprise-authentication-mechanisms` diff --git a/source/fundamentals/crud.txt b/source/fundamentals/crud.txt deleted file mode 100644 index 3fcff3c9..00000000 --- a/source/fundamentals/crud.txt +++ /dev/null @@ -1,29 +0,0 @@ -.. _golang-crud: - -=============== -CRUD Operations -=============== - -.. meta:: - :description: Explore how to perform CRUD operations using the MongoDB Go Driver, including creating, reading, updating, and deleting documents. - -.. toctree:: - :caption: CRUD Operations - - Read - Write - Compound Operations - Modify CRUD Execution - -CRUD (Create, Read, Update, Delete) operations enable you to work with -data stored in MongoDB. - -- :ref:`golang-crud-read-operations` find and return - documents stored in your database. -- :ref:`golang-crud-write-operations` insert, modify, - or delete documents in your database. - -Some operations combine aspects of read and write operations. To learn -more about these hybrid methods, see :ref:`golang-compound-operations`. - -To learn about how to modify the way your CRUD operations execute, see :ref:`golang-write-read-pref`. \ No newline at end of file diff --git a/source/get-started.txt b/source/get-started.txt new file mode 100644 index 00000000..fafad122 --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,119 @@ +.. _go-get-started: + +======================== +Getting Started with Go +======================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Learn how to create an app to connect to MongoDB deployment by using the Go driver. + :keywords: node.js + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. adapted from quick start, should be checked + +.. 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='' + + .. note:: + + Make sure to replace the ```` 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 ` 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 diff --git a/source/index.txt b/source/index.txt index 536b2048..3294efdb 100644 --- a/source/index.txt +++ b/source/index.txt @@ -10,25 +10,29 @@ :description: Learn how to use the MongoDB Go Driver. :keywords: landing page, index +.. TODO cleanup + .. toctree:: :titlesonly: :maxdepth: 1 - Quick Start - Quick Reference - What's New - Usage Examples - Fundamentals + Get Started + Connect + Databases & Collections + CRUD Operations + Aggregation + Data Formats + Indexes + Run a Database Command + Atlas Search + Atlas Vector Search + Monitoring & Logging + Security + Reference API Documentation <{+api+}/mongo> - FAQ - Connection Troubleshooting Issues & Help - Compatibility View the Source -.. - /upgrade - Introduction ------------ diff --git a/source/fundamentals/indexes.txt b/source/indexes.txt similarity index 100% rename from source/fundamentals/indexes.txt rename to source/indexes.txt diff --git a/source/monitoring-and-logging.txt b/source/monitoring-and-logging.txt new file mode 100644 index 00000000..e0972dad --- /dev/null +++ b/source/monitoring-and-logging.txt @@ -0,0 +1,25 @@ +.. _golang-monitoring-logging: + +====================== +Monitoring and Logging +====================== + +.. meta:: + :keywords: event + :description: Learn how to monitor and log events by using the {+driver-long+}. + +.. toctree:: + + Monitoring + Logging + Change Streams + +Overview +-------- + +Learn how to set up monitoring and logging for your application in the following +sections: + +- :doc:`/monitoring-and-logging/monitoring` +- :doc:`/monitoring-and-logging/logging` +- :doc:`/monitoring-and-logging/change-streams` diff --git a/source/monitoring-and-logging/change-streams.txt b/source/monitoring-and-logging/change-streams.txt new file mode 100644 index 00000000..e42a8671 --- /dev/null +++ b/source/monitoring-and-logging/change-streams.txt @@ -0,0 +1,10 @@ +.. _golang-watch-changes: +.. _golang-monitor-changes: +.. _golang-watch: +.. _golang-usageex-monitor-changes: + +================================ +Monitor Data with Change Streams +================================ + +.. TODO \ No newline at end of file diff --git a/source/fundamentals/logging.txt b/source/monitoring-and-logging/logging.txt similarity index 100% rename from source/fundamentals/logging.txt rename to source/monitoring-and-logging/logging.txt diff --git a/source/monitoring-and-logging/monitoring.txt b/source/monitoring-and-logging/monitoring.txt new file mode 100644 index 00000000..07dfc328 --- /dev/null +++ b/source/monitoring-and-logging/monitoring.txt @@ -0,0 +1,24 @@ +.. _golang-monitoring: + +========================== +Monitor Application Events +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. meta:: + :description: Explore cluster, command, and connection pool monitoring in the MongoDB Go Driver. + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: event + :description: Learn how to monitor events by using the {+driver-long+}. + +.. TODO diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 00000000..9819683b --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,16 @@ +.. _golang-reference: + +========== +Reference +========== + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Upgrade Guides + Previous Versions + Quick Reference + \ No newline at end of file diff --git a/source/reference/compatibility.txt b/source/reference/compatibility.txt new file mode 100644 index 00000000..3333cc07 --- /dev/null +++ b/source/reference/compatibility.txt @@ -0,0 +1,36 @@ +.. _golang-compatibility: + +============= +Compatibility +============= + +.. meta:: + :description: Check the recommended MongoDB Go Driver versions for compatibility with different MongoDB server versions. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +MongoDB Compatibility +--------------------- + +The following compatibility table specifies the recommended version of the +{+driver-long+} for use with a specific version of MongoDB. + +The first column lists the driver version. + +.. sharedinclude:: dbx/lifecycle-schedule-callout.rst + +.. sharedinclude:: dbx/compatibility-table-legend.rst + +.. include:: /includes/mongodb-compatibility-table-go.rst + +Language Compatibility +---------------------- + +.. include:: /includes/language-compatibility-table-go.rst + +For more information on how to read the compatibility tables, see our guide on +:ref:`MongoDB Compatibility Tables. ` diff --git a/source/reference/previous-versions.txt b/source/reference/previous-versions.txt new file mode 100644 index 00000000..e9caea9c --- /dev/null +++ b/source/reference/previous-versions.txt @@ -0,0 +1 @@ +.. TODO verify if needed \ No newline at end of file diff --git a/source/reference/quick-reference.txt b/source/reference/quick-reference.txt new file mode 100644 index 00000000..93a7cc37 --- /dev/null +++ b/source/reference/quick-reference.txt @@ -0,0 +1,479 @@ +.. _golang-quick-reference: + +=============== +Quick Reference +=============== + +.. meta:: + :description: Explore with the MongoDB Go Driver syntax for various commands, including find, insert, update, delete, and more, with links to API documentation and usage examples. + +.. default-domain:: mongodb + +This page shows the driver syntax for several MongoDB commands and links to +their related reference and API documentation. + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Command + - Syntax + + * - | **Find a Document** + | + | `API Documentation <{+api+}/mongo#Collection.FindOne>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + err = coll.FindOne(context.TODO(), bson.D{{"firstName", Mike}}).Decode(&result) + + .. output:: + :language: go + :visible: false + + [{firstName Mike}, {lastName Smith} ...] + + * - | **Find Multiple Documents** + | + | `API Documentation <{+api+}/mongo#Collection.Find>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find(context.TODO(), bson.D{{"age", bson.D{{"$gte", 46}}}}) + + .. output:: + :language: go + :visible: false + + [{firstName Kyle}, {age 51}, ... ] + [{firstName Omar}, {age 47}, ... ] + + * - | **Insert a Document** + | + | `API Documentation <{+api+}/mongo#Collection.InsertOne>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. code-block:: go + :copyable: true + + result, err := coll.InsertOne( + context.TODO(), + bson.D{ + {"animal", "Dog"}, + {"breed", "Beagle"} + } + ) + + * - | **Insert Multiple Documents** + | + | `API Documentation <{+api+}/mongo#Collection.InsertMany>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. code-block:: go + :copyable: true + + docs := []interface{} { + bson.D{{"firstName", "Erik"}, {"age", 27}}, + bson.D{{"firstName", "Mohammad"}, {"lastName", "Ahmad"}, {"age", 10}}, + bson.D{{"firstName", "Todd"}}, + bson.D{{"firstName", "Juan"}, {"lastName", "Pablo"}} + } + + result, err := coll.InsertMany(context.TODO(), docs) + + * - | **Update a Document** + | + | `API Documentation <{+api+}/mongo#Collection.UpdateOne>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + result, err := coll.UpdateOne( + context.TODO(), + bson.D{{"firstName", "Erik"}}, + bson.D{{"$set", bson.D{{"age", 28}}}} + ) + fmt.Printf("The number of modified documents: %d\n", result.ModifiedCount) + + .. output:: + :language: go + :visible: false + + The number of modified documents: 1 + + * - | **Update Multiple Documents** + | + | `API Documentation <{+api+}/mongo#Collection.UpdateMany>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + result, err := coll.UpdateMany( + context.TODO(), + bson.D{{"age", bson.D{{"$gte", 58}}}}, + bson.D{{"$set", bson.D{{"description", "Senior"}}}} + ) + fmt.Printf("The number of modified documents: %d\n", result.ModifiedCount) + + .. output:: + :language: go + :visible: false + + The number of modified documents: 4 + + * - | **Update Arrays in Documents** + | + | `API Documentation <{+api+}/mongo#Collection.UpdateMany>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + result, err := coll.UpdateMany( + context.TODO(), + bson.D{}, + bson.D{{"$push", bson.D{{family, "brother"}}}} + ) + + .. output:: + :language: go + :visible: false + + [{firstName Xiao}, {family ["brother"]}, ... ] + [{firstName Omar}, {family ["brother", "mother"]}, ... ] + ... + + * - | **Replace a Document** + | + | `API Documentation <{+api+}/mongo#Collection.ReplaceOne>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + result, err := coll.ReplaceOne( + context.TODO(), + bson.D{{"firstName", "Mick"}}, + bson.D{{"firstName", "Mike"}, {"lastName", "Doe"}} + ) + + .. output:: + :language: go + :visible: false + + [{{firstName Mike}, {lastName Doe} }] + + * - | **Delete a Document** + | + | `API Documentation <{+api+}/mongo#Collection.DeleteOne>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. code-block:: go + :copyable: true + + result, err := coll.DeleteOne( + context.TODO(), + bson.D{{"firstName", "Xiao"}} + ) + + * - | **Delete Multiple Documents** + | + | `API Documentation <{+api+}/mongo#Collection.DeleteMany>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. code-block:: go + :copyable: true + + results, err := coll.DeleteMany( + context.TODO(), + bson.D{{"age", bson.D{{"$lte", 12}}}} + ) + + * - | **Bulk Write** + | + | `API Documentation <{+api+}/mongo#Collection.BulkWrite>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + models := []mongo.WriteModel{ + mongo.NewInsertOneModel().SetDocument(bson.D{{"firstName", "John"}, {"age", 5}}), + mongo.NewUpdateOneModel().SetFilter(bson.D{{"firstName", "Juan"}}). + SetUpdate(bson.D{{"$set", bson.D{{"age", 12}}}}), + } + opts := options.BulkWrite().SetOrdered(true) + + results, err := coll.BulkWrite(context.TODO(), models, opts) + + .. output:: + :language: go + :visible: false + + [{firstName John}, {age 5} ... ] + [{firstName Juan}, {age 12} ... ] + + * - | **Monitor Data Changes** + | + | `API Documentation <{+api+}/mongo#Collection.Watch>`__ + | :ref:`Usage Example ` + + - .. code-block:: go + :copyable: true + + pipeline := mongo.Pipeline{bson.D{{"$match", bson.D{{"operationType", "insert"}}}}} + cs, err := coll.Watch(context.TODO(), pipeline) + + * - | **Access Data from a Cursor Iteratively** + | + | `API Documentation <{+api+}/mongo#Cursor.Next>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find(context.TODO(), bson.D{}) + + for cursor.Next(context.TODO()) { + var result bson.D + if err := cursor.Decode(&result); err != nil { + log.Fatal(err) + } + fmt.Println(result) + } + + .. output:: + :language: go + :visible: false + + [{firstName Doug} ... ] + [{firstName Erik} ...] + [{lastName Chang} ...] + ... + + * - | **Access Data from a Cursor as an Array** + | + | `API Documentation <{+api+}/mongo#Cursor.All>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find(context.TODO(), bson.D{}) + + var results []bson.D + if err = cursor.All(context.TODO(), &results); err != nil { + panic(err) + } + + .. output:: + :language: go + :visible: false + + [{name Mike} ... ] + [{name Edgar} ...] + [{name Freddie} ...] + ... + + * - | **Count Documents** + | + | `API Documentation <{+api+}/mongo#Collection.CountDocuments>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + count, err := coll.CountDocuments(context.TODO(), bson.D{}) + + .. output:: + :language: go + :visible: false + + 6 + + * - | **List the Distinct Documents or Field Values** + | `API Documentation <{+api+}/mongo#Collection.Distinct>`__ + | :ref:`Usage Example ` + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + var results []string + err = coll.Distinct(context.TODO(), "firstName", bson.D{}).Decode(&results) + + .. output:: + :language: go + :visible: false + + [Mike Xiao Sandy ...] + + * - | **Limit the Number of Documents Retrieved** + | + | `API Documentation <{+api+}/mongo/options#FindOptionsBuilder.SetLimit>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find(context.TODO(), bson.D{}, options.Find().SetLimit(2)) + + .. output:: + :language: go + :visible: false + + [{breed Beagle} ... ] + [{breed German Shepard} ...] + + * - | **Skip Retrieved Documents** + | + | `API Documentation <{+api+}/mongo/options#FindOptionsBuilder.SetSkip>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + // the collection has 6 documents + cursor, err := coll.Find(context.TODO(), bson.D{}, options.Find().SetSkip(4)) + + .. output:: + :language: go + :visible: false + + [{item Pen} ... ] + [{item Chair} ...] + + * - | **Sort the Documents When Retrieving Them** + | + | `API Documentation <{+api+}/mongo/options#FindOptionsBuilder.SetSort>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find(context.TODO(), bson.D{}, options.Find().SetSort(bson.D{{"age", 1}})) + + .. output:: + :language: go + :visible: false + + [{firstName Dev} {age 5} ... ] + [{firstName Jose} {age 7} ... ] + [{firstName Om} {age 8} ... ] + + * - | **Project Document Fields When Retrieving Them** + | + | `API Documentation <{+api+}/mongo/options#FindOptionsBuilder.SetProjection>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + cursor, err := coll.Find( + context.TODO(), + bson.D{}, + options.Find().SetProjection( + bson.D{{"age", 0}, {"_id",0}} + ) + ) + + .. output:: + :language: go + :visible: false + + [{firstName Lester}] + [{firstName Wendall} {lastName Griffin}] + ... + + * - | **Create an Index** + | + | `API Documentation <{+api+}/mongo#IndexView.CreateOne>`__ + | :ref:`Fundamentals ` + + - .. code-block:: go + :copyable: true + + model := mongo.IndexModel{Keys: bson.D{{"firstName", 1}, {"lastName", -1}}} + name, err := coll.Indexes().CreateOne(context.TODO(), model) + + * - | **Search Text** + | + | `API Documentation <{+api+}/mongo#Collection.Find>`__ + | :ref:`Fundamentals ` + + - .. io-code-block:: + :copyable: true + + .. input:: + :language: go + + // only searches fields with text indexes + cursor, err := coll.Find(context.TODO(), bson.D{{"$text", bson.D{{"$search", "beagle"}}}}) + + .. output:: + :language: go + :visible: false + + [{"firstName": "Emily" , "Description": "I love to play sports and walk my beagle."} ... ] diff --git a/source/whats-new.txt b/source/reference/release-notes.txt similarity index 99% rename from source/whats-new.txt rename to source/reference/release-notes.txt index 12f5354b..717481e5 100644 --- a/source/whats-new.txt +++ b/source/reference/release-notes.txt @@ -1,8 +1,11 @@ .. _golang-whats-new: +.. _golang-release-notes: -========== -What's New -========== +.. TODO clean up + +============= +Release Notes +============= .. contents:: On this page :local: diff --git a/source/reference/upgrade.txt b/source/reference/upgrade.txt new file mode 100644 index 00000000..39fb839e --- /dev/null +++ b/source/reference/upgrade.txt @@ -0,0 +1,2 @@ +.. TODO + diff --git a/source/fundamentals/run-command.txt b/source/run-command.txt similarity index 100% rename from source/fundamentals/run-command.txt rename to source/run-command.txt diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 00000000..efa60261 --- /dev/null +++ b/source/security.txt @@ -0,0 +1,37 @@ +.. _golang-security: + +================ +Secure Your Data +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ldap, encryption, principal, tls, authorize, boto, ecs, aws + :description: Learn how to use {+driver-short+} to secure your data. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Authentication + In-Use Encryption + TLS Security Protocol + +Overview +-------- + +Learn how to set up security and authentication for your application +in the following sections: + +- :ref:`Authentication ` +- :ref:`In-Use Encryption ` +- :ref:`TLS Security Protocol ` diff --git a/source/security/authentication.txt b/source/security/authentication.txt new file mode 100644 index 00000000..b97791f7 --- /dev/null +++ b/source/security/authentication.txt @@ -0,0 +1,75 @@ +.. _golang-enterprise-authentication-mechanisms: +.. _golang-authentication-mechanisms: + +========================= +Authentication Mechanisms +========================= + +.. meta:: + :description: Authenticate using the MongoDB Go Driver with various supported authentication mechanisms. + +.. default-domain:: mongodb + +.. toctree:: + + SCRAM + X.509 + AWS IAM + OIDC + LDAP (PLAIN) + Kerberos (GSSAPI) + +.. TODO make sure correct + +Overview +-------- + +In this guide, you can learn how to authenticate to MongoDB by using the +**authentication mechanisms** available in {+mdb-server+}. +Authentication mechanisms are processes by which the driver and server confirm +the identity of a client to ensure security before connecting. + +.. tip:: Connecting to MongoDB + + To learn how to establish a connection to your MongoDB deployment, see the + :ref:`golang-connect` guide. + +MongoDB Edition Compatibility +----------------------------- + +The following table lists the authentication mechanisms supported by MongoDB and +the {+mdb-server+} editions that each mechanism is compatible with. Click the name of +a mechanism to learn more about how to use it with your application. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Authentication Mechanism + - Atlas + - Enterprise Advanced + - Community + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - No + - No + * - :ref:`` + - Yes + - Yes + - No + * - :ref:`` + - Yes + - Yes + - No + * - :ref:`` + - No + - Yes + - No \ No newline at end of file diff --git a/source/fundamentals/encrypt-fields.txt b/source/security/encrypt-fields.txt similarity index 100% rename from source/fundamentals/encrypt-fields.txt rename to source/security/encrypt-fields.txt diff --git a/source/security/tls.txt b/source/security/tls.txt new file mode 100644 index 00000000..2eb2b2d3 --- /dev/null +++ b/source/security/tls.txt @@ -0,0 +1,7 @@ +.. _golang-tls: + +========================== +Enable TLS on a Connection +========================== + +.. TODO \ No newline at end of file