Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
141 changes: 130 additions & 11 deletions source/crud/query/retrieve.txt
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ consist of the ``Find()`` and ``FindOne()`` methods.

.. _golang-find-example:

Find All Documents
~~~~~~~~~~~~~~~~~~
Find Multiple Documents
~~~~~~~~~~~~~~~~~~~~~~~

The ``Find()`` method expects you to pass a ``Context`` type and a
query filter. The method returns *all* documents that match the filter
Expand Down Expand Up @@ -94,6 +94,66 @@ the ``Find()`` method, which performs the following actions:

To learn how to access data by using a cursor, see the :ref:`golang-cursor` guide.

Find Multiple Documents Example: Full File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/usage-examples/example-intro.rst

The following example finds all documents in the ``restaurants`` collection
in which the value of ``cuisine`` is ``"Italian"``. The example returns a cursor that
references the matched documents and unpacks the documents into a slice.
Select the :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:

.. tabs::

.. tab :: Struct
:tabid: structExample

The following code uses structs to find and return all documents in the
``restaurants`` collection in which the value of ``cuisine`` is "Italian":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/find.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

// results truncated
...
{ ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... },
{ ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... },
{ ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... },
...

.. tab :: bson.D
:tabid: bsonDExample

The following code uses a bson.D type to find and return all documents in
the ``restaurants`` collection in which the value of ``cuisine`` is "Italian":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/findBsonD.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

// results truncated
...
{ ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... },
{ ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... },
{ ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... },
...

.. _golang-find-one-example:

Find One Document
Expand Down Expand Up @@ -182,6 +242,73 @@ as parameters to the ``FindOne()`` method to perform the following actions:
about the ``_id`` field, see the :ref:`_id Field <golang-insert-id>`
section of the Insert a Document page.

Find One Document Example: Full File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/usage-examples/example-intro.rst

The following example finds a document in the ``restaurants`` collection that
matches a query filter. Select the :guilabel:`Struct` or :guilabel:`bson.D`
tab to see the corresponding code:

.. tabs::

.. tab :: Struct
:tabid: structExample

The following code uses structs to find and return the first document in the
``restaurants`` collection in which the value of ``name`` is "Bagels N Buns":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/findOne.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

// results truncated
{
"ID": "5eb3d668b31de5d588f42950",
"Name": "Bagels N Buns",
"RestaurantId": "40363427"
"Address": [...],
"Borough": "Staten Island",
"Cuisine": "Delicatessen",
"Grades": [...]
}

.. tab :: bson.D
:tabid: bsonDExample

The following code uses a bson.D type to find and return the first document
in the ``restaurants`` collection in which the value of ``name`` is "Bagels N Buns":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/findOneBsonD.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

// results truncated
{
"ID": "5eb3d668b31de5d588f42950",
"Name": "Bagels N Buns",
"RestaurantId": "40363427"
"Address": [...],
"Borough": "Staten Island",
"Cuisine": "Delicatessen",
"Grades": [...]
}

.. _golang-retrieve-options:

Modify Behavior
Expand Down Expand Up @@ -330,20 +457,12 @@ the MongoDB server manual page on :manual:`Aggregation
Additional Information
----------------------

For runnable examples of the find operations, see the following usage
examples:

- :ref:`golang-find-one`
- :ref:`golang-find-multiple`

To learn more about the operations mentioned, see the following
guides:

- :ref:`golang-query-document`
- :ref:`golang-cursor`
- :ref:`golang-skip`
- :ref:`golang-sort-results`
- :ref:`golang-limit`
- :ref:`Specify Documents to Return <golang-specify-documents-to-return>`
- :ref:`golang-project`
- :ref:`golang-aggregation`
- :ref:`golang-collations`
Expand Down
11 changes: 6 additions & 5 deletions source/includes/usage-examples/code-snippets/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// start-restaurant-struct
// Creates a Restaurant struct as a model for documents in the restaurants collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string
Expand All @@ -25,7 +25,10 @@ type Restaurant struct {
Grades interface{}
}

// end-restaurant-struct
// Creates a filter struct to use for the query
type RestaurantCuisineFilter struct {
Cuisine string
}

func main() {
if err := godotenv.Load(); err != nil {
Expand All @@ -47,12 +50,11 @@ func main() {
}
}()

// begin find
coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates a query filter to match documents in which the "cuisine"
// is "Italian"
filter := bson.D{{"cuisine", "Italian"}}
filter := RestaurantCuisineFilter{Cuisine: "Italian"}

// Retrieves documents that match the query filter
cursor, err := coll.Find(context.TODO(), filter)
Expand All @@ -65,7 +67,6 @@ func main() {
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
// end find

// Prints the results of the find operation as structs
for _, result := range results {
Expand Down
64 changes: 64 additions & 0 deletions source/includes/usage-examples/code-snippets/findBsonD.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Retrieves documents that match a query filter by using the Go driver
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"os"

"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}

var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#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)
}
}()

coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates a query filter to match documents in which the "cuisine"
// is "Italian"
filter := bson.D{{"cuisine", "Italian"}}

// Retrieves documents that match the query filter
cursor, err := coll.Find(context.TODO(), filter)
if err != nil {
panic(err)
}

// Unpacks the cursor into a slice
var results []Restaurant
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}

// Prints the results of the find operation as structs
for _, result := range results {
cursor.Decode(&result)
output, err := json.MarshalIndent(result, "", " ")
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this Decode intentional? It seems like it wouldn't do anything since all of the cursor results are already fetched and decoded by calling cursor.All above.

If it's not intentional, the same line needs to be removed from find.go also.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Deleted!

if err != nil {
panic(err)
}
fmt.Printf("%s\n", output)
}
}
11 changes: 6 additions & 5 deletions source/includes/usage-examples/code-snippets/findOne.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// start-restaurant-struct
// Creates a Restaurant struct as a model for documents in the restaurants collection
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string
Expand All @@ -25,7 +25,10 @@ type Restaurant struct {
Grades []interface{}
}

// end-restaurant-struct
// Creates a filter struct to use for the query
type RestaurantNameFilter struct {
Name string
}

func main() {
if err := godotenv.Load(); err != nil {
Expand All @@ -47,12 +50,11 @@ func main() {
}
}()

// begin findOne
coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates a query filter to match documents in which the "name" is
// "Bagels N Buns"
filter := bson.D{{"name", "Bagels N Buns"}}
filter := RestaurantNameFilter{Name: "Bagels N Buns"}

// Retrieves the first matching document
var result Restaurant
Expand All @@ -66,7 +68,6 @@ func main() {
}
panic(err)
}
// end findOne

output, err := json.MarshalIndent(result, "", " ")
if err != nil {
Expand Down
61 changes: 61 additions & 0 deletions source/includes/usage-examples/code-snippets/findOneBsonD.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Retrieves a document that matches a query filter by using the Go driver
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"os"

"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}

var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#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)
}
}()

coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates a query filter to match documents in which the "name" is
// "Bagels N Buns"
filter := bson.D{{"name", "Bagels N Buns"}}

// Retrieves the first matching document
var result Restaurant
err = coll.FindOne(context.TODO(), filter).Decode(&result)

// Prints a message if no documents are matched or if any
// other errors occur during the operation
if err != nil {
if err == mongo.ErrNoDocuments {
return
}
panic(err)
}

output, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", output)
}
Loading