Skip to content

DOCSP-47020 Databases and collections #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 139 additions & 1 deletion source/databases-collections.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,142 @@
Databases and Collections
=========================

.. TODO

.. 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 </core/document/>` 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
</reference/command/create>` 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.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[note for reviewer] I opted not to add a Read/Write Concern section that is in some of the examples in the ticket because that info will be in the new Configure CRUD Operations page.


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>`__
85 changes: 85 additions & 0 deletions source/includes/databases-collections.go
Original file line number Diff line number Diff line change
@@ -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
}
6 changes: 6 additions & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
---------------

Expand Down
Loading