Skip to content

Commit f44f352

Browse files
authored
DOCSP-47020 Databases and collections (#504)
1 parent ef26268 commit f44f352

File tree

3 files changed

+230
-1
lines changed

3 files changed

+230
-1
lines changed

source/databases-collections.txt

Lines changed: 139 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,142 @@
44
Databases and Collections
55
=========================
66

7-
.. TODO
7+
8+
.. contents:: On this page
9+
:local:
10+
:backlinks: none
11+
:depth: 2
12+
:class: singlecol
13+
14+
.. facet::
15+
:name: genre
16+
:values: reference
17+
18+
.. meta::
19+
:keywords: table, row, organize, storage, code example
20+
:description: Learn how to manage MongoDB databases and collections using the Go driver, including accessing, creating, and deleting collections.
21+
22+
Overview
23+
--------
24+
25+
In this guide, you can learn how to interact with MongoDB databases and
26+
collections by using the {+driver-short+}.
27+
28+
MongoDB organizes data into a hierarchy of the following levels:
29+
30+
- **Databases**: Top-level data structures in a MongoDB deployment that store
31+
collections.
32+
- **Collections**: Groups of MongoDB documents. They are analogous to tables in
33+
relational databases.
34+
- **Documents**: Units that store literal data such as strings, numbers, dates,
35+
and other embedded documents. For more information about document field types
36+
and structure, see the :manual:`Documents </core/document/>` entry in the
37+
{+mdb-server+} manual.
38+
39+
Access a Database
40+
-----------------
41+
42+
You can access a database by using the ``Database()`` method on a ``Client``
43+
instance.
44+
45+
The following example accesses a database named ``test_database``:
46+
47+
.. literalinclude:: /includes/databases-collections.go
48+
:start-after: start-access-database
49+
:end-before: end-access-database
50+
:language: go
51+
:copyable:
52+
:dedent:
53+
54+
Access a Collection
55+
-------------------
56+
57+
You can access a collection by using the ``Collection()`` method on a
58+
``Database`` instance.
59+
60+
The following example accesses a collection named ``test_collection``:
61+
62+
.. literalinclude:: /includes/databases-collections.go
63+
:start-after: start-access-collection
64+
:end-before: end-access-collection
65+
:language: go
66+
:copyable:
67+
:dedent:
68+
69+
.. tip::
70+
71+
If the provided collection name does not already exist in the database,
72+
MongoDB implicitly creates the collection when you first insert data into it.
73+
74+
Create a Collection
75+
-------------------
76+
77+
To explicity create a collection, you can use the ``CreateCollection()`` method
78+
on a ``Database`` instance.
79+
80+
The following example creates a collection named ``example_collection``:
81+
82+
.. literalinclude:: /includes/databases-collections.go
83+
:start-after: start-create-collection
84+
:end-before: end-create-collection
85+
:language: go
86+
:copyable:
87+
:dedent:
88+
89+
You can specify collection options, such as maximum size and document validation
90+
rules, by passing an ``options.CreateCollectionOptions`` struct to the
91+
``CreateCollection()`` method of a ``Database`` instance. For a full list of
92+
optional parameters, see the :manual:`create command
93+
</reference/command/create>` entry in the {+mdb-server+} manual.
94+
95+
Get a List of Collections
96+
-------------------------
97+
98+
You can query for a list of collections in a database by using the
99+
``ListCollections()`` method on a ``Database`` instance.
100+
101+
The following example gets a list of all the collections in a database, and then
102+
prints the collection names to the console:
103+
104+
.. literalinclude:: /includes/databases-collections.go
105+
:start-after: start-list-collections
106+
:end-before: end-list-collections
107+
:language: go
108+
:copyable:
109+
:dedent:
110+
111+
Delete a Collection
112+
-------------------
113+
114+
You can delete a collection by using the ``Drop()`` method on a ``Database``
115+
instance.
116+
117+
The following example deletes a collection named
118+
``test_collection``:
119+
120+
.. literalinclude:: /includes/databases-collections.go
121+
:start-after: start-delete-collection
122+
:end-before: end-delete-collection
123+
:language: go
124+
:copyable:
125+
:dedent:
126+
127+
.. warning:: Dropping a Collection Deletes All Data in the Collection
128+
129+
Dropping a collection from your database permanently deletes all documents
130+
and all indexes within that collection.
131+
132+
Drop a collection only if you no longer need the data in that collection.
133+
134+
API Documentation
135+
-----------------
136+
137+
To learn more about any of the types or methods discussed in this guide, see the
138+
following API documentation:
139+
140+
- `Client <{+api+}/mongo#Client>`__
141+
- `Database <{+api+}/mongo#Database>`__
142+
- `Collection <{+api+}/mongo#Collection>`__
143+
- `CreateCollection() <{+api+}/mongo#Database.CreateCollection>`__
144+
- `ListCollections() <{+api+}/mongo#Database.ListCollections>`__
145+
- `Drop() <{+api+}/mongo#Database.Drop>`__
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
9+
"go.mongodb.org/mongo-driver/v2/bson"
10+
"go.mongodb.org/mongo-driver/v2/mongo"
11+
"go.mongodb.org/mongo-driver/v2/mongo/options"
12+
)
13+
14+
func main() {
15+
uri := os.Getenv("MONGODB_URI")
16+
docs := "www.mongodb.com/docs/drivers/go/current/"
17+
if uri == "" {
18+
log.Fatal("Set your 'MONGODB_URI' environment variable. " +
19+
"See: " + docs +
20+
"usage-examples/#environment-variable")
21+
}
22+
client, err := mongo.Connect(options.Client().
23+
ApplyURI(uri))
24+
if err != nil {
25+
panic(err)
26+
}
27+
28+
defer func() {
29+
if err := client.Disconnect(context.TODO()); err != nil {
30+
panic(err)
31+
}
32+
}()
33+
34+
// Accesses the test_database database
35+
// start-access-database
36+
database := client.Database("test_database")
37+
// end-access-database
38+
39+
// Accesses the test_collection collection
40+
// start-access-collection
41+
collection := database.Collection("test_collection")
42+
// end-access-collection
43+
fmt.Println("Collection accessed:", collection.Name())
44+
45+
// Explicitly creates a collection in the database
46+
// start-create-collection
47+
err = database.CreateCollection(context.TODO(), "example_collection")
48+
if err != nil {
49+
log.Fatalf("Failed to create collection: %v", err)
50+
}
51+
// end-create-collection
52+
53+
// Retrieves information about each colllection in the database
54+
// start-list-collections
55+
cursor, err := database.ListCollections(context.TODO(), bson.D{})
56+
if err != nil {
57+
log.Fatalf("Failed to list collections: %v", err)
58+
}
59+
defer cursor.Close(context.TODO())
60+
61+
for cursor.Next(context.TODO()) {
62+
var collectionInfo bson.M
63+
if err := cursor.Decode(&collectionInfo); err != nil {
64+
log.Fatalf("Failed to decode collection info: %v", err)
65+
}
66+
if name, ok := collectionInfo["name"].(string); ok {
67+
fmt.Println(name)
68+
} else {
69+
log.Println("Collection name not found or not a string")
70+
}
71+
}
72+
73+
if err := cursor.Err(); err != nil {
74+
log.Fatalf("Cursor error: %v", err)
75+
}
76+
// end-list-collections
77+
78+
// Deletes the test_collection collection
79+
// start-delete-collection
80+
err = database.Collection("test_collection").Drop(context.TODO())
81+
if err != nil {
82+
log.Fatalf("Failed to drop collection: %v", err)
83+
}
84+
// end-delete-collection
85+
}

source/index.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ Quick Start
5555
Learn how to establish a connection to MongoDB Atlas and begin
5656
working with data in the :ref:`golang-quickstart` section.
5757

58+
Databases and Collections
59+
-------------------------
60+
61+
Learn how to interact with MongoDB databases and collections in the
62+
:ref:`golang-databases-collections` section.
63+
5864
Quick Reference
5965
---------------
6066

0 commit comments

Comments
 (0)