-
Notifications
You must be signed in to change notification settings - Fork 34
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
stephmarie17
merged 4 commits into
mongodb:comp-cov
from
stephmarie17:docsp-47020-collectionManagement
Jun 4, 2025
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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>`__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// 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 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.