From 45c63225a8e2fbec92f45c8a2c618715a9849117 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Fri, 30 May 2025 09:50:07 -0700 Subject: [PATCH 1/4] add guide and code example --- source/databases-collections.txt | 135 ++++++++++++++++++++++- source/includes/databases-collections.go | 84 ++++++++++++++ source/index.txt | 6 + 3 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 source/includes/databases-collections.go diff --git a/source/databases-collections.txt b/source/databases-collections.txt index fc96f0ca..65d92cef 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -4,4 +4,137 @@ Databases and Collections ========================= -.. TODO \ No newline at end of file + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: table, row, organize, storage, code example + :description: Learn how to manage MongoDB databases and collections using the Go driver, including accessing, creating, and deleting collections, and configuring read and write operations. + +Overview +-------- + +In this guide, you can learn how to interact with MongoDB databases and +collections by using the {+driver-short+}. + +MongoDB organizes data into a hierarchy of the following levels: + +- **Databases**: Top-level data structures in a MongoDB deployment that store + collections. +- **Collections**: Groups of MongoDB documents. They are analogous to tables in + relational databases. +- **Documents**: Units that store literal data such as strings, numbers, dates, + and other embedded documents. For more information about document field types + and structure, see the :manual:`Documents ` entry in the + {+mdb-server+} manual. + +Access a Database +----------------- + +You can access a database by using the ``Database()`` method on a ``Client`` +instance. + +The following example accesses a database named ``test_database``: + +.. literalinclude:: /includes/databases-collections.go + :start-after: start-access-database + :end-before: end-access-database + :language: go + :copyable: + :dedent: + +Access a Collection +------------------- + +You can access a collection by using the ``Collection()`` method on a +``Database`` instance. + +The following example accesses a collection named ``test_collection`` in the +``test_database`` database: + +.. literalinclude:: /includes/databases-collections.go + :start-after: start-access-collection + :end-before: end-access-collection + :language: go + :copyable: + :dedent: + +.. tip:: + + If the provided collection name does not already exist in the database, + MongoDB implicitly creates the collection when you first insert data into it. + +Create a Collection +------------------- + +To explicity create a collection, you can use the ``CreateCollection()`` method +on a ``Database`` instance. + +The following example creates a collectioned named ``example_collection``: + +.. literalinclude:: /includes/databases-collections.go + :start-after: start-create-collection + :end-before: end-create-collection + :language: go + :copyable: + :dedent: + +You can specify collection options, such as maximum size and document validation +rules, by passing a ``options.CreateCollectionOptions`` struct to the +``CreateCollection()`` method of a ``Database`` instance. For a full list of +optional parameters, see the :manual:`create command +` entry in the {+mdb-server+} manual. + +Get a List of Collections +------------------------- + +You can query for a list of collections in a database by using the +``ListCollections()`` method on a ``Database`` instance. + +.. literalinclude:: /includes/databases-collections.go + :start-after: start-list-collections + :end-before: end-list-collections + :language: go + :copyable: + :dedent: + +Delete a Collection +------------------- + +You can delete a collection by using the ``Drop()`` method on a ``Database`` +instance. + +.. literalinclude:: /includes/databases-collections.go + :start-after: start-delete-collection + :end-before: end-delete-collection + :language: go + :copyable: + :dedent: + +.. warning:: Dropping a Collection Deletes All Data in the Collection + + Dropping a collection from your database permanently deletes all documents + and all indexes within that collection. + + Drop a collection only if the data in it is no longer needed. + +API Documentation +----------------- + +To learn more about any of the types or methods discussed in this guide, see the +following API documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `Database <{+api+}/mongo#Database>`__ +- `Collection <{+api+}/mongo#Collection>`__ +- `CreateCollection() <{+api+}/mongo#Database.CreateCollection>`__ +- `ListCollections() <{+api+}/mongo#Database.ListCollections>`__ +- `Drop() <{+api+}/mongo#Database.Drop>`__ \ No newline at end of file diff --git a/source/includes/databases-collections.go b/source/includes/databases-collections.go new file mode 100644 index 00000000..f8511f48 --- /dev/null +++ b/source/includes/databases-collections.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "fmt" + "log" + "os" + + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" +) + +func main() { + uri := os.Getenv("MONGODB_URI") + docs := "www.mongodb.com/docs/drivers/go/current/" + if uri == "" { + log.Fatal("Set your 'MONGODB_URI' environment variable. " + + "See: " + docs + + "usage-examples/#environment-variable") + } + client, err := mongo.Connect(options.Client(). + ApplyURI(uri)) + if err != nil { + panic(err) + } + + defer func() { + if err := client.Disconnect(context.TODO()); err != nil { + panic(err) + } + }() + + // Accesses the test_database database + // start-access-database + database := client.Database("test_database") + // end-access-database + + // Accesses the test_collection collection + // start-access-collection + collection := database.Collection("test_collection") + // end-access-collection + + // Explicitly creates a collection in the database + // start-create-collection + err = database.CreateCollection(context.TODO(), "example_collection") + if err != nil { + log.Fatalf("Failed to create collection: %v", err) + } + // end-create-collection + + // Retrieves information about each colllection in the database + // start-list-collections + cursor, err := database.ListCollections(context.TODO(), bson.M{}, options.ListCollections()) + if err != nil { + log.Fatalf("Failed to list collections: %v", err) + } + defer cursor.Close(context.TODO()) + + for cursor.Next(context.TODO()) { + var collectionInfo bson.M + if err := cursor.Decode(&collectionInfo); err != nil { + log.Fatalf("Failed to decode collection info: %v", err) + } + if name, ok := collectionInfo["name"].(string); ok { + fmt.Println(name) + } else { + log.Println("Collection name not found or not a string") + } + } + + if err := cursor.Err(); err != nil { + log.Fatalf("Cursor error: %v", err) + } + // end-list-collections + + // Deletes the test_collection collection + // start-delete-collection + err = database.Collection("test_collection").Drop(context.TODO()) + if err != nil { + log.Fatalf("Failed to drop collection: %v", err) + } + // end-delete-collection +} diff --git a/source/index.txt b/source/index.txt index 3294efdb..b4a27204 100644 --- a/source/index.txt +++ b/source/index.txt @@ -55,6 +55,12 @@ Quick Start Learn how to establish a connection to MongoDB Atlas and begin working with data in the :ref:`golang-quickstart` section. +Databases and Collections +------------------------- + +Learn how to interact with MongoDB databases and collections in the +:ref:`golang-databases-collections` section. + Quick Reference --------------- From 340715c3f9f571dde586d98ca170ba854fbe7cb9 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Fri, 30 May 2025 10:34:45 -0700 Subject: [PATCH 2/4] edits --- source/databases-collections.txt | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/source/databases-collections.txt b/source/databases-collections.txt index 65d92cef..ad21146c 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -17,7 +17,7 @@ Databases and Collections .. meta:: :keywords: table, row, organize, storage, code example - :description: Learn how to manage MongoDB databases and collections using the Go driver, including accessing, creating, and deleting collections, and configuring read and write operations. + :description: Learn how to manage MongoDB databases and collections using the Go driver, including accessing, creating, and deleting collections. Overview -------- @@ -57,8 +57,7 @@ Access a Collection You can access a collection by using the ``Collection()`` method on a ``Database`` instance. -The following example accesses a collection named ``test_collection`` in the -``test_database`` database: +The following example accesses a collection named ``test_collection``: .. literalinclude:: /includes/databases-collections.go :start-after: start-access-collection @@ -78,7 +77,7 @@ Create a Collection To explicity create a collection, you can use the ``CreateCollection()`` method on a ``Database`` instance. -The following example creates a collectioned named ``example_collection``: +The following example creates a collection named ``example_collection``: .. literalinclude:: /includes/databases-collections.go :start-after: start-create-collection @@ -88,7 +87,7 @@ The following example creates a collectioned named ``example_collection``: :dedent: You can specify collection options, such as maximum size and document validation -rules, by passing a ``options.CreateCollectionOptions`` struct to the +rules, by passing an ``options.CreateCollectionOptions`` struct to the ``CreateCollection()`` method of a ``Database`` instance. For a full list of optional parameters, see the :manual:`create command ` entry in the {+mdb-server+} manual. @@ -99,6 +98,9 @@ Get a List of Collections You can query for a list of collections in a database by using the ``ListCollections()`` method on a ``Database`` instance. +The following example gets a list of all the collections in a database, and then +prints the collection names to the console: + .. literalinclude:: /includes/databases-collections.go :start-after: start-list-collections :end-before: end-list-collections From 83f8161dd45c465d26d41e0fb3d22442ac5ce43d Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 2 Jun 2025 09:17:35 -0700 Subject: [PATCH 3/4] mm feedback --- source/databases-collections.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source/databases-collections.txt b/source/databases-collections.txt index ad21146c..8a2b26a9 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -114,6 +114,9 @@ Delete a Collection You can delete a collection by using the ``Drop()`` method on a ``Database`` instance. +The following example deletes a collection named +``test_collection``: + .. literalinclude:: /includes/databases-collections.go :start-after: start-delete-collection :end-before: end-delete-collection @@ -126,7 +129,7 @@ instance. Dropping a collection from your database permanently deletes all documents and all indexes within that collection. - Drop a collection only if the data in it is no longer needed. + Drop a collection only if you no longer need the data in that collection. API Documentation ----------------- From 61f74cb918a62baa1178bc450c4b3f14a0db8fef Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Wed, 4 Jun 2025 14:44:19 -0700 Subject: [PATCH 4/4] tech feedback --- source/includes/databases-collections.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/includes/databases-collections.go b/source/includes/databases-collections.go index f8511f48..4d2a0f2e 100644 --- a/source/includes/databases-collections.go +++ b/source/includes/databases-collections.go @@ -40,6 +40,7 @@ func main() { // start-access-collection collection := database.Collection("test_collection") // end-access-collection + fmt.Println("Collection accessed:", collection.Name()) // Explicitly creates a collection in the database // start-create-collection @@ -51,7 +52,7 @@ func main() { // Retrieves information about each colllection in the database // start-list-collections - cursor, err := database.ListCollections(context.TODO(), bson.M{}, options.ListCollections()) + cursor, err := database.ListCollections(context.TODO(), bson.D{}) if err != nil { log.Fatalf("Failed to list collections: %v", err) }