From 42d6f9856a2129aec16b2b4ca0fceddab43aef4b Mon Sep 17 00:00:00 2001 From: Lindsey Moore Date: Wed, 16 Jul 2025 14:39:12 -0400 Subject: [PATCH 1/5] DOCSP-51815 Move and standardize find usage exs --- source/crud/query/retrieve.txt | 134 +++++++++++++++++- .../usage-examples/code-snippets/find.go | 14 +- .../usage-examples/code-snippets/findBsonD.go | 67 +++++++++ .../usage-examples/code-snippets/findOne.go | 14 +- .../code-snippets/findOneBsonD.go | 64 +++++++++ 5 files changed, 281 insertions(+), 12 deletions(-) create mode 100644 source/includes/usage-examples/code-snippets/findBsonD.go create mode 100644 source/includes/usage-examples/code-snippets/findOneBsonD.go diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index ae6603f3..d9162943 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -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 @@ -94,6 +94,67 @@ 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 documents in the ``restaurants`` collection +in which the ``cuisine`` is ``"Italian"``, returns a cursor that +references the matched documents, then unpacks the documents into a slice. +Select the **Struct** or **bson.D** tab to see the corresponding code: + +.. tabs:: + + .. tab :: Struct + :tabid: structExample + + The following code uses structs to find documents in the ``restaurants`` collection + in which the ``cuisine`` is "Italian", returning all documents that match: + + .. 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 documents in the ``restaurants`` + collection in which the ``cuisine`` is "Italian", returning all documents + that match: + + .. 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 @@ -182,6 +243,75 @@ as parameters to the ``FindOne()`` method to perform the following actions: about the ``_id`` field, see the :ref:`_id Field ` 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 that matches a query filter in the +``restaurants`` collection. Select the **Struct** or **bson.D** tab to see the +corresponding code: + +.. tabs:: + + .. tab :: Struct + :tabid: structExample + + The following code uses structs to find documents in the ``restaurants`` collection + in which the ``name`` is "Bagels N Buns", returning the first document + matched: + + .. 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 documents in the ``restaurants`` collection + in which the ``name`` is "Bagels N Buns", returning the first document + matched: + + .. 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 diff --git a/source/includes/usage-examples/code-snippets/find.go b/source/includes/usage-examples/code-snippets/find.go index a70573c8..0c430b51 100644 --- a/source/includes/usage-examples/code-snippets/find.go +++ b/source/includes/usage-examples/code-snippets/find.go @@ -1,3 +1,4 @@ +// begin find // Retrieves documents that match a query filter by using the Go driver package main @@ -14,7 +15,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 @@ -25,7 +26,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 { @@ -47,12 +51,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) @@ -65,7 +68,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 { @@ -77,3 +79,5 @@ func main() { fmt.Printf("%s\n", output) } } + +// end find diff --git a/source/includes/usage-examples/code-snippets/findBsonD.go b/source/includes/usage-examples/code-snippets/findBsonD.go new file mode 100644 index 00000000..eead83cd --- /dev/null +++ b/source/includes/usage-examples/code-snippets/findBsonD.go @@ -0,0 +1,67 @@ +// begin find +// 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, "", " ") + if err != nil { + panic(err) + } + fmt.Printf("%s\n", output) + } +} + +// end find diff --git a/source/includes/usage-examples/code-snippets/findOne.go b/source/includes/usage-examples/code-snippets/findOne.go index e3ba4447..33639f82 100644 --- a/source/includes/usage-examples/code-snippets/findOne.go +++ b/source/includes/usage-examples/code-snippets/findOne.go @@ -1,3 +1,4 @@ +// begin findOne // Retrieves a document that matches a query filter by using the Go driver package main @@ -14,7 +15,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 @@ -25,7 +26,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 { @@ -47,12 +51,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 @@ -66,7 +69,6 @@ func main() { } panic(err) } - // end findOne output, err := json.MarshalIndent(result, "", " ") if err != nil { @@ -74,3 +76,5 @@ func main() { } fmt.Printf("%s\n", output) } + +// end findOne diff --git a/source/includes/usage-examples/code-snippets/findOneBsonD.go b/source/includes/usage-examples/code-snippets/findOneBsonD.go new file mode 100644 index 00000000..b04adfe4 --- /dev/null +++ b/source/includes/usage-examples/code-snippets/findOneBsonD.go @@ -0,0 +1,64 @@ +// begin findOne +// 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) +} + +// end findOne From ab0d783d0c122efda73bdd635989d209a24901a3 Mon Sep 17 00:00:00 2001 From: Lindsey Moore Date: Wed, 16 Jul 2025 14:56:26 -0400 Subject: [PATCH 2/5] small fixes --- source/crud/query/retrieve.txt | 6 ------ source/includes/usage-examples/code-snippets/find.go | 3 --- source/includes/usage-examples/code-snippets/findBsonD.go | 3 --- source/includes/usage-examples/code-snippets/findOne.go | 3 --- .../includes/usage-examples/code-snippets/findOneBsonD.go | 3 --- 5 files changed, 18 deletions(-) diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index d9162943..2d74ed4d 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -460,12 +460,6 @@ 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: diff --git a/source/includes/usage-examples/code-snippets/find.go b/source/includes/usage-examples/code-snippets/find.go index 0c430b51..4186e34b 100644 --- a/source/includes/usage-examples/code-snippets/find.go +++ b/source/includes/usage-examples/code-snippets/find.go @@ -1,4 +1,3 @@ -// begin find // Retrieves documents that match a query filter by using the Go driver package main @@ -79,5 +78,3 @@ func main() { fmt.Printf("%s\n", output) } } - -// end find diff --git a/source/includes/usage-examples/code-snippets/findBsonD.go b/source/includes/usage-examples/code-snippets/findBsonD.go index eead83cd..331fe7eb 100644 --- a/source/includes/usage-examples/code-snippets/findBsonD.go +++ b/source/includes/usage-examples/code-snippets/findBsonD.go @@ -1,4 +1,3 @@ -// begin find // Retrieves documents that match a query filter by using the Go driver package main @@ -63,5 +62,3 @@ func main() { fmt.Printf("%s\n", output) } } - -// end find diff --git a/source/includes/usage-examples/code-snippets/findOne.go b/source/includes/usage-examples/code-snippets/findOne.go index 33639f82..b180e77b 100644 --- a/source/includes/usage-examples/code-snippets/findOne.go +++ b/source/includes/usage-examples/code-snippets/findOne.go @@ -1,4 +1,3 @@ -// begin findOne // Retrieves a document that matches a query filter by using the Go driver package main @@ -76,5 +75,3 @@ func main() { } fmt.Printf("%s\n", output) } - -// end findOne diff --git a/source/includes/usage-examples/code-snippets/findOneBsonD.go b/source/includes/usage-examples/code-snippets/findOneBsonD.go index b04adfe4..6a605c6c 100644 --- a/source/includes/usage-examples/code-snippets/findOneBsonD.go +++ b/source/includes/usage-examples/code-snippets/findOneBsonD.go @@ -1,4 +1,3 @@ -// begin findOne // Retrieves a document that matches a query filter by using the Go driver package main @@ -60,5 +59,3 @@ func main() { } fmt.Printf("%s\n", output) } - -// end findOne From 37c8403730c1bdde6339f506e087e0bbb9a46df9 Mon Sep 17 00:00:00 2001 From: Lindsey Moore Date: Wed, 16 Jul 2025 15:09:17 -0400 Subject: [PATCH 3/5] fix --- source/crud/query/retrieve.txt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index 2d74ed4d..557656e4 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -465,9 +465,7 @@ guides: - :ref:`golang-query-document` - :ref:`golang-cursor` -- :ref:`golang-skip` -- :ref:`golang-sort-results` -- :ref:`golang-limit` +- :ref:`Specify Documents to Return ` - :ref:`golang-project` - :ref:`golang-aggregation` - :ref:`golang-collations` From b480a37e139d7d069801f480bc916fc602bcf48f Mon Sep 17 00:00:00 2001 From: Lindsey Moore Date: Mon, 21 Jul 2025 19:34:07 -0400 Subject: [PATCH 4/5] MB review --- source/crud/query/retrieve.txt | 35 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index 557656e4..dafbd0a0 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -99,18 +99,18 @@ Find Multiple Documents Example: Full File .. include:: /includes/usage-examples/example-intro.rst -The following example finds documents in the ``restaurants`` collection -in which the ``cuisine`` is ``"Italian"``, returns a cursor that -references the matched documents, then unpacks the documents into a slice. -Select the **Struct** or **bson.D** tab to see the corresponding code: +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 documents in the ``restaurants`` collection - in which the ``cuisine`` is "Italian", returning all documents that match: + 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 @@ -133,9 +133,8 @@ Select the **Struct** or **bson.D** tab to see the corresponding code: .. tab :: bson.D :tabid: bsonDExample - The following code uses a bson.D type to find documents in the ``restaurants`` - collection in which the ``cuisine`` is "Italian", returning all documents - that match: + 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 @@ -248,18 +247,17 @@ Find One Document Example: Full File .. include:: /includes/usage-examples/example-intro.rst -The following example finds a document that matches a query filter in the -``restaurants`` collection. Select the **Struct** or **bson.D** tab to see the -corresponding code: +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 documents in the ``restaurants`` collection - in which the ``name`` is "Bagels N Buns", returning the first document - matched: + 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 @@ -286,10 +284,9 @@ corresponding code: .. tab :: bson.D :tabid: bsonDExample - The following code uses a bson.D type to find documents in the ``restaurants`` collection - in which the ``name`` is "Bagels N Buns", returning the first document - matched: - + 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 From d90913256e9344bd046b7dea139b3ebea551ade2 Mon Sep 17 00:00:00 2001 From: Lindsey Moore Date: Fri, 25 Jul 2025 18:24:05 -0400 Subject: [PATCH 5/5] tech feedback --- source/crud/query/retrieve.txt | 148 +++++------------- .../usage-examples/code-snippets/find.go | 8 +- .../usage-examples/code-snippets/findBsonD.go | 64 -------- .../usage-examples/code-snippets/findOne.go | 7 +- .../code-snippets/findOneBsonD.go | 61 -------- 5 files changed, 41 insertions(+), 247 deletions(-) delete mode 100644 source/includes/usage-examples/code-snippets/findBsonD.go delete mode 100644 source/includes/usage-examples/code-snippets/findOneBsonD.go diff --git a/source/crud/query/retrieve.txt b/source/crud/query/retrieve.txt index dafbd0a0..5d1cb4ae 100644 --- a/source/crud/query/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -101,58 +101,25 @@ Find Multiple Documents Example: Full File 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: +references the matched documents and unpacks the documents into a slice: -.. 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 +.. io-code-block:: + :copyable: true - .. input:: /includes/usage-examples/code-snippets/findBsonD.go - :language: go - :dedent: + .. input:: /includes/usage-examples/code-snippets/find.go + :language: go + :dedent: - .. output:: - :language: none - :visible: false + .. 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", ... }, - ... + // 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: @@ -247,67 +214,30 @@ 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": [...] - } +The following example finds and returns 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": [...] + } .. _golang-retrieve-options: diff --git a/source/includes/usage-examples/code-snippets/find.go b/source/includes/usage-examples/code-snippets/find.go index 4186e34b..97ad4833 100644 --- a/source/includes/usage-examples/code-snippets/find.go +++ b/source/includes/usage-examples/code-snippets/find.go @@ -25,11 +25,6 @@ type Restaurant struct { Grades interface{} } -// Creates a filter struct to use for the query -type RestaurantCuisineFilter struct { - Cuisine string -} - func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") @@ -54,7 +49,7 @@ func main() { // Creates a query filter to match documents in which the "cuisine" // is "Italian" - filter := RestaurantCuisineFilter{Cuisine: "Italian"} + filter := bson.D{{"cuisine", "Italian"}} // Retrieves documents that match the query filter cursor, err := coll.Find(context.TODO(), filter) @@ -70,7 +65,6 @@ func main() { // Prints the results of the find operation as structs for _, result := range results { - cursor.Decode(&result) output, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) diff --git a/source/includes/usage-examples/code-snippets/findBsonD.go b/source/includes/usage-examples/code-snippets/findBsonD.go deleted file mode 100644 index 331fe7eb..00000000 --- a/source/includes/usage-examples/code-snippets/findBsonD.go +++ /dev/null @@ -1,64 +0,0 @@ -// 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, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("%s\n", output) - } -} diff --git a/source/includes/usage-examples/code-snippets/findOne.go b/source/includes/usage-examples/code-snippets/findOne.go index b180e77b..4483e7ba 100644 --- a/source/includes/usage-examples/code-snippets/findOne.go +++ b/source/includes/usage-examples/code-snippets/findOne.go @@ -25,11 +25,6 @@ type Restaurant struct { Grades []interface{} } -// Creates a filter struct to use for the query -type RestaurantNameFilter struct { - Name string -} - func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") @@ -54,7 +49,7 @@ func main() { // Creates a query filter to match documents in which the "name" is // "Bagels N Buns" - filter := RestaurantNameFilter{Name: "Bagels N Buns"} + filter := bson.D{{"name", "Bagels N Buns"}} // Retrieves the first matching document var result Restaurant diff --git a/source/includes/usage-examples/code-snippets/findOneBsonD.go b/source/includes/usage-examples/code-snippets/findOneBsonD.go deleted file mode 100644 index 6a605c6c..00000000 --- a/source/includes/usage-examples/code-snippets/findOneBsonD.go +++ /dev/null @@ -1,61 +0,0 @@ -// 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) -}