...

Text file src/go.mongodb.org/mongo-driver/README.md

Documentation: go.mongodb.org/mongo-driver

     1<p align="center"><img src="etc/assets/mongo-gopher.png" width="250"></p>
     2<p align="center">
     3  <a href="https://goreportcard.com/report/go.mongodb.org/mongo-driver"><img src="https://goreportcard.com/badge/go.mongodb.org/mongo-driver"></a>
     4  <a href="https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo"><img src="etc/assets/godev-mongo-blue.svg" alt="docs"></a>
     5  <a href="https://pkg.go.dev/go.mongodb.org/mongo-driver/bson"><img src="etc/assets/godev-bson-blue.svg" alt="docs"></a>
     6  <a href="https://www.mongodb.com/docs/drivers/go/current/"><img src="etc/assets/docs-mongodb-green.svg"></a>
     7</p>
     8
     9# MongoDB Go Driver
    10
    11The MongoDB supported driver for Go.
    12
    13______________________________________________________________________
    14
    15## Requirements
    16
    17- Go 1.18 or higher. We aim to support the latest versions of Go.
    18- Go 1.20 or higher is required to run the driver test suite.
    19- MongoDB 3.6 and higher.
    20
    21______________________________________________________________________
    22
    23## Installation
    24
    25The recommended way to get started using the MongoDB Go driver is by using Go modules to install the dependency in
    26your project. This can be done either by importing packages from `go.mongodb.org/mongo-driver` and having the build
    27step install the dependency or by explicitly running
    28
    29```bash
    30go get go.mongodb.org/mongo-driver/mongo
    31```
    32
    33When using a version of Go that does not support modules, the driver can be installed using `dep` by running
    34
    35```bash
    36dep ensure -add "go.mongodb.org/mongo-driver/mongo"
    37```
    38
    39______________________________________________________________________
    40
    41## Usage
    42
    43To get started with the driver, import the `mongo` package and create a `mongo.Client` with the `Connect` function:
    44
    45```go
    46import (
    47    "context"
    48    "time"
    49
    50    "go.mongodb.org/mongo-driver/mongo"
    51    "go.mongodb.org/mongo-driver/mongo/options"
    52    "go.mongodb.org/mongo-driver/mongo/readpref"
    53)
    54
    55ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    56defer cancel()
    57client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    58```
    59
    60Make sure to defer a call to `Disconnect` after instantiating your client:
    61
    62```go
    63defer func() {
    64    if err = client.Disconnect(ctx); err != nil {
    65        panic(err)
    66    }
    67}()
    68```
    69
    70For more advanced configuration and authentication, see the [documentation for mongo.Connect](https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Connect).
    71
    72Calling `Connect` does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to,
    73use the `Ping` method:
    74
    75```go
    76ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    77defer cancel()
    78err = client.Ping(ctx, readpref.Primary())
    79```
    80
    81To insert a document into a collection, first retrieve a `Database` and then `Collection` instance from the `Client`:
    82
    83```go
    84collection := client.Database("testing").Collection("numbers")
    85```
    86
    87The `Collection` instance can then be used to insert documents:
    88
    89```go
    90ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
    91defer cancel()
    92res, err := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
    93id := res.InsertedID
    94```
    95
    96To use `bson.D`, you will need to add `"go.mongodb.org/mongo-driver/bson"` to your imports.
    97
    98Your import statement should now look like this:
    99
   100```go
   101import (
   102    "context"
   103    "log"
   104    "time"
   105
   106    "go.mongodb.org/mongo-driver/bson"
   107    "go.mongodb.org/mongo-driver/mongo"
   108    "go.mongodb.org/mongo-driver/mongo/options"
   109    "go.mongodb.org/mongo-driver/mongo/readpref"
   110)
   111```
   112
   113Several query methods return a cursor, which can be used like this:
   114
   115```go
   116ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
   117defer cancel()
   118cur, err := collection.Find(ctx, bson.D{})
   119if err != nil { log.Fatal(err) }
   120defer cur.Close(ctx)
   121for cur.Next(ctx) {
   122    var result bson.D
   123    err := cur.Decode(&result)
   124    if err != nil { log.Fatal(err) }
   125    // do something with result....
   126}
   127if err := cur.Err(); err != nil {
   128    log.Fatal(err)
   129}
   130```
   131
   132For methods that return a single item, a `SingleResult` instance is returned:
   133
   134```go
   135var result struct {
   136    Value float64
   137}
   138filter := bson.D{{"name", "pi"}}
   139ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
   140defer cancel()
   141err = collection.FindOne(ctx, filter).Decode(&result)
   142if err == mongo.ErrNoDocuments {
   143    // Do something when no record was found
   144    fmt.Println("record does not exist")
   145} else if err != nil {
   146    log.Fatal(err)
   147}
   148// Do something with result...
   149```
   150
   151Additional examples and documentation can be found under the examples directory and [on the MongoDB Documentation website](https://www.mongodb.com/docs/drivers/go/current/).
   152
   153### Network Compression
   154
   155Network compression will reduce bandwidth requirements between MongoDB and the application.
   156
   157The Go Driver supports the following compression algorithms:
   158
   1591. [Snappy](https://google.github.io/snappy/) (`snappy`): available in MongoDB 3.4 and later.
   1601. [Zlib](https://zlib.net/) (`zlib`): available in MongoDB 3.6 and later.
   1611. [Zstandard](https://github.com/facebook/zstd/) (`zstd`): available in MongoDB 4.2 and later.
   162
   163#### Specify Compression Algorithms
   164
   165Compression can be enabled using the `compressors` parameter on the connection string or by using [`ClientOptions.SetCompressors`](https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo/options#ClientOptions.SetCompressors):
   166
   167```go
   168opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")
   169client, _ := mongo.Connect(context.TODO(), opts)
   170```
   171
   172```go
   173opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"})
   174client, _ := mongo.Connect(context.TODO(), opts)
   175```
   176
   177If compressors are set, the Go Driver negotiates with the server to select the first common compressor. For server configuration and defaults, refer to [`networkMessageCompressors`](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--networkMessageCompressors).
   178
   179Messages compress when both parties enable network compression; otherwise, messages remain uncompressed
   180
   181______________________________________________________________________
   182
   183## Feedback
   184
   185For help with the driver, please post in the [MongoDB Community Forums](https://developer.mongodb.com/community/forums/tag/golang/).
   186
   187New features and bugs can be reported on jira: https://jira.mongodb.org/browse/GODRIVER
   188
   189______________________________________________________________________
   190
   191## Contribution
   192
   193Check out the [project page](https://jira.mongodb.org/browse/GODRIVER) for tickets that need completing. See our [contribution guidelines](docs/CONTRIBUTING.md) for details.
   194
   195______________________________________________________________________
   196
   197## Continuous Integration
   198
   199Commits to master are run automatically on [evergreen](https://evergreen.mongodb.com/waterfall/mongo-go-driver).
   200
   201______________________________________________________________________
   202
   203## Frequently Encountered Issues
   204
   205See our [common issues](docs/common-issues.md) documentation for troubleshooting frequently encountered issues.
   206
   207______________________________________________________________________
   208
   209## Thanks and Acknowledgement
   210
   211- The Go Gopher artwork by [@ashleymcnamara](https://github.com/ashleymcnamara)
   212- The original Go Gopher was designed by [Renee French](http://reneefrench.blogspot.com/)
   213
   214______________________________________________________________________
   215
   216## License
   217
   218The MongoDB Go Driver is licensed under the [Apache License](LICENSE).

View as plain text