Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The Official Golang driver for MongoDB

License

NotificationsYou must be signed in to change notification settings

mongodb/mongo-go-driver

docsdocsOpenSSF Scorecard

MongoDB Go Driver

The MongoDB supported driver for Go.

See the following resources to learn more about upgrading from version 1.x to 2.0.:

The MongoDB Go driver followssemantic versioning for its releases.

Requirements

  • Go 1.19 or higher. We aim to support the latest versions of Go.
  • Go 1.25 or higher is required to run the driver test suite.
  • MongoDB 4.2 and higher.

Installation

The recommended way to get started using the MongoDB Go driver is by using Go modules to install the dependency inyour project. This can be done either by importing packages fromgo.mongodb.org/mongo-driver and having the buildstep install the dependency or by explicitly running

go get go.mongodb.org/mongo-driver/v2/mongo

When using a version of Go that does not support modules, the driver can be installed usingdep by running

dep ensure -add"go.mongodb.org/mongo-driver/v2/mongo"

Usage

To get started with the driver, import themongo package and create amongo.Client with theConnect function:

import ("context""time""go.mongodb.org/mongo-driver/v2/mongo""go.mongodb.org/mongo-driver/v2/mongo/options""go.mongodb.org/mongo-driver/v2/mongo/readpref")client,_:=mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))

Make sure to defer a call toDisconnect after instantiating your client:

deferfunc() {iferr:=client.Disconnect(ctx);err!=nil {panic(err)    }}()

For more advanced configuration and authentication, see thedocumentation for mongo.Connect.

CallingConnect does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to,use thePing method:

ctx,cancel:=context.WithTimeout(context.Background(),2*time.Second)defercancel()_=client.Ping(ctx,readpref.Primary())

To insert a document into a collection, first retrieve aDatabase and thenCollection instance from theClient:

collection:=client.Database("testing").Collection("numbers")

TheCollection instance can then be used to insert documents:

ctx,cancel:=context.WithTimeout(context.Background(),5*time.Second)defercancel()res,_:=collection.InsertOne(ctx, bson.D{{"name","pi"}, {"value",3.14159}})id:=res.InsertedID

To usebson.D, you will need to add"go.mongodb.org/mongo-driver/v2/bson" to your imports.

Your import statement should now look like this:

import ("context""log""time""go.mongodb.org/mongo-driver/v2/bson""go.mongodb.org/mongo-driver/v2/mongo""go.mongodb.org/mongo-driver/v2/mongo/options""go.mongodb.org/mongo-driver/v2/mongo/readpref")

Several query methods return a cursor, which can be used like this:

ctx,cancel:=context.WithTimeout(context.Background(),30*time.Second)defercancel()cur,err:=collection.Find(ctx, bson.D{})iferr!=nil {log.Fatal(err)}defercur.Close(ctx)forcur.Next(ctx) {varresult bson.Diferr:=cur.Decode(&result);err!=nil {log.Fatal(err)    }// do something with result....}iferr:=cur.Err();err!=nil {log.Fatal(err)}

For methods that return a single item, aSingleResult instance is returned:

varresultstruct {Valuefloat64}filter:= bson.D{{"name","pi"}}ctx,cancel:=context.WithTimeout(context.Background(),5*time.Second)defercancel()err:=collection.FindOne(ctx,filter).Decode(&result)iferrors.Is(err,mongo.ErrNoDocuments) {// Do something when no record was found}elseiferr!=nil {log.Fatal(err)}// Do something with result...

Additional examples and documentation can be found under the examples directory andon the MongoDB Documentation website.

Network Compression

Network compression will reduce bandwidth requirements between MongoDB and the application.

The Go Driver supports the following compression algorithms:

  1. Snappy (snappy): available in MongoDB 3.4 and later.
  2. Zlib (zlib): available in MongoDB 3.6 and later.
  3. Zstandard (zstd): available in MongoDB 4.2 and later.

Specify Compression Algorithms

Compression can be enabled using thecompressors parameter on the connection string or by usingClientOptions.SetCompressors:

opts:=options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")client,_:=mongo.Connect(opts)
opts:=options.Client().SetCompressors([]string{"snappy","zlib","zstd"})client,_:=mongo.Connect(opts)

If compressors are set, the Go Driver negotiates with the server to select the first common compressor. For server configuration and defaults, refer tonetworkMessageCompressors.

Messages compress when both parties enable network compression; otherwise, messages remain uncompressed

Support / Feedback

For issues with, questions about, or feedback for the Go Driver, please look into oursupport channels, includingStackOverflow.

New features and bugs can be reported on theGODRIVER Jira project.

Contribution

Check out theGODRIVER Jira project for tickets that need completing. See ourcontribution guidelines for details.

Continuous Integration

Commits to master are run automatically onevergreen.

Frequently Encountered Issues

See ourcommon issues documentation for troubleshooting frequently encountered issues.

Thanks and Acknowledgement

License

The MongoDB Go Driver is licensed under theApache License.

Packages

No packages published

Contributors168

Languages


[8]ページ先頭

©2009-2026 Movatter.jp