diff --git a/source/databases-collections.txt b/source/databases-collections.txt index fc96f0ca..8a2b26a9 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -4,4 +4,142 @@ 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. + +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``: + +.. 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 collection 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 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. + +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 + :language: go + :copyable: + :dedent: + +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 + :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 you no longer need the data in that collection. + +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..4d2a0f2e --- /dev/null +++ b/source/includes/databases-collections.go @@ -0,0 +1,85 @@ +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 + fmt.Println("Collection accessed:", collection.Name()) + + // 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.D{}) + 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 ---------------