mongo
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package mongo provides a MongoDB Driver API for Go.
Basic usage of the driver starts with creating a Client from a connectionstring. To do so, call Connect:
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)defer cancel()client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))if err != nil { return err }This will create a new client and start monitoring the MongoDB server on localhost.The Database and Collection types can be used to access the database:
collection := client.Database("baz").Collection("qux")A Collection can be used to query the database or insert documents:
res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})if err != nil { return err }id := res.InsertedIDSeveral methods return a cursor, which can be used like this:
cur, err := collection.Find(context.Background(), bson.D{})if err != nil { log.Fatal(err) }defer cur.Close(context.Background())for cur.Next(context.Background()) { // To decode into a struct, use cursor.Decode() result := struct{ Foo string Bar int32 }{} err := cur.Decode(&result) if err != nil { log.Fatal(err) } // do something with result... // To get the raw bson bytes use cursor.Current raw := cur.Current // do something with raw...}if err := cur.Err(); err != nil { return err}Cursor.All will decode all of the returned elements at once:
var results []struct{ Foo string Bar int32}if err = cur.All(context.Background(), &results); err != nil { log.Fatal(err)}// do something with results...Methods that only return a single document will return a *SingleResult, which workslike a *sql.Row:
result := struct{ Foo string Bar int32}{}filter := bson.D{{"hello", "world"}}err := collection.FindOne(context.Background(), filter).Decode(&result)if err != nil { return err }// do something with result...All Client, Collection, and Database methods that take parameters of type interface{}will return ErrNilDocument if nil is passed in for an interface{}.
Additional examples can be found under the examples directory in the driver's repository andon the MongoDB website.
Error Handling¶
Errors from the MongoDB server will implement the ServerError interface, which has functions to check for specificerror codes, labels, and message substrings. These can be used to check for and handle specific errors. Some methods,like InsertMany and BulkWrite, can return an error representing multiple errors, and in those cases the ServerErrorfunctions will return true if any of the contained errors satisfy the check.
There are also helper functions to check for certain specific types of errors:
IsDuplicateKeyError(error)IsNetworkError(error)IsTimeout(error)
Potential DNS Issues¶
Building with Go 1.11+ and using connection strings with the "mongodb+srv"[1] scheme is unfortunatelyincompatible with some DNS servers in the wild due to the change introduced inhttps://github.com/golang/go/issues/10622. You may receive an error with the message "cannot unmarshal DNS message"while running an operation when using DNS servers that non-compliantly compress SRV records. Old versions of kube-dnsand the native DNS resolver (systemd-resolver) on Ubuntu 18.04 are known to be non-compliant in this manner. We suggestusing a different DNS server (8.8.8.8 is the common default), and, if that's not possible, avoiding the "mongodb+srv"scheme.
Client Side Encryption¶
Client-side encryption is a new feature in MongoDB 4.2 that allows specific data fields to be encrypted. Using thisfeature requires specifying the "cse" build tag during compilation:
go build -tags cse
Note: Auto encryption is an enterprise- and Atlas-only feature.
The libmongocrypt C library is required when using client-side encryption. Specific versions of libmongocryptare required for different versions of the Go Driver:
- Go Driver v1.2.0 requires libmongocrypt v1.0.0 or higher
- Go Driver v1.5.0 requires libmongocrypt v1.1.0 or higher
- Go Driver v1.8.0 requires libmongocrypt v1.3.0 or higher
- Go Driver v1.10.0 requires libmongocrypt v1.5.0 or higher.There is a severe bug when calling RewrapManyDataKey with libmongocrypt versions less than 1.5.2.This bug may result in data corruption.Please use libmongocrypt 1.5.2 or higher when calling RewrapManyDataKey.
- Go Driver v1.12.0 requires libmongocrypt v1.8.0 or higher.
To install libmongocrypt, follow the instructions for youroperating system:
1. Linux: follow the instructions listed athttps://github.com/mongodb/libmongocrypt#installing-libmongocrypt-from-distribution-packages to install the correctdeb/rpm package.
2. Mac: Follow the instructions listed athttps://github.com/mongodb/libmongocrypt#installing-libmongocrypt-on-macosto install packages via brew and compile the libmongocrypt source code.
3. Windows:
mkdir -p c:/libmongocrypt/binmkdir -p c:/libmongocrypt/include// Run the curl command in an empty directory as it will create new directories when unpacked.curl https://s3.amazonaws.com/mciuploads/libmongocrypt/windows/latest_release/libmongocrypt.tar.gz --output libmongocrypt.tar.gztar -xvzf libmongocrypt.tar.gzcp ./bin/mongocrypt.dll c:/libmongocrypt/bincp ./include/mongocrypt/*.h c:/libmongocrypt/includeexport PATH=$PATH:/cygdrive/c/libmongocrypt/bin
libmongocrypt communicates with the mongocryptd process or mongo_crypt shared library for automatic encryption.See AutoEncryptionOpts.SetExtraOptions for options to configure use of mongocryptd or mongo_crypt.
[1] Seehttps://www.mongodb.com/docs/manual/reference/connection-string/#dns-seedlist-connection-format
Example (ClientSideEncryption)¶
// This would have to be the same master key that was used to create the// encryption key.localKey := make([]byte, 96)if _, err := rand.Read(localKey); err != nil {log.Panic(err)}kmsProviders := map[string]map[string]interface{}{"local": {"key": localKey,},}keyVaultNamespace := "encryption.__keyVault"uri := "mongodb://localhost:27017"autoEncryptionOpts := options.AutoEncryption().SetKeyVaultNamespace(keyVaultNamespace).SetKmsProviders(kmsProviders)clientOpts := options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOpts)client, err := Connect(context.TODO(), clientOpts)if err != nil {log.Panicf("Connect error: %v", err)}defer func() {if err = client.Disconnect(context.TODO()); err != nil {log.Panicf("Disconnect error: %v", err)}}()collection := client.Database("test").Collection("coll")if err := collection.Drop(context.TODO()); err != nil {log.Panicf("Collection.Drop error: %v", err)}_, err = collection.InsertOne(context.TODO(),bson.D{{"encryptedField", "123456789"}})if err != nil {log.Panicf("InsertOne error: %v", err)}res, err := collection.FindOne(context.TODO(), bson.D{}).Raw()if err != nil {log.Panicf("FindOne error: %v", err)}fmt.Println(res)Example (ClientSideEncryptionCreateKey)¶
keyVaultNamespace := "encryption.__keyVault"uri := "mongodb://localhost:27017"// kmsProviders would have to be populated with the correct KMS provider// information before it's used.var kmsProviders map[string]map[string]interface{}// Create Client and ClientEncryptionclientEncryptionOpts := options.ClientEncryption().SetKeyVaultNamespace(keyVaultNamespace).SetKmsProviders(kmsProviders)keyVaultClient, err := Connect(context.TODO(),options.Client().ApplyURI(uri))if err != nil {log.Panicf("Connect error for keyVaultClient: %v", err)}clientEnc, err := NewClientEncryption(keyVaultClient, clientEncryptionOpts)if err != nil {log.Panicf("NewClientEncryption error: %v", err)}defer func() {// this will disconnect the keyVaultClient as wellif err = clientEnc.Close(context.TODO()); err != nil {log.Panicf("Close error: %v", err)}}()// Create a new data key and encode it as base64dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), "local")if err != nil {log.Panicf("CreateDataKey error: %v", err)}dataKeyBase64 := base64.StdEncoding.EncodeToString(dataKeyID.Data)// Create a JSON schema using the new data key. This schema could also be// written in a separate file and read in using I/O functions.schema := `{"properties": {"encryptedField": {"encrypt": {"keyId": [{"$binary": {"base64": "%s","subType": "04"}}],"bsonType": "string","algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"}}},"bsonType": "object"}`schema = fmt.Sprintf(schema, dataKeyBase64)var schemaDoc bson.Rawerr = bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc)if err != nil {log.Panicf("UnmarshalExtJSON error: %v", err)}// Configure a Client with auto encryption using the new schemadbName := "test"collName := "coll"schemaMap := map[string]interface{}{dbName + "." + collName: schemaDoc,}autoEncryptionOpts := options.AutoEncryption().SetKmsProviders(kmsProviders).SetKeyVaultNamespace(keyVaultNamespace).SetSchemaMap(schemaMap)clientOptions := options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOpts)client, err := Connect(context.TODO(), clientOptions)if err != nil {log.Panicf("Connect error for encrypted client: %v", err)}defer func() {_ = client.Disconnect(context.TODO())}()// Use client for operations.Example (ExplictEncryption)¶
// localMasterKey must be the same master key that was used to create the// encryption key.var localMasterKey []bytekmsProviders := map[string]map[string]interface{}{"local": {"key": localMasterKey,},}// The MongoDB namespace (db.collection) used to store the encryption data// keys.keyVaultDBName, keyVaultCollName := "encryption", "testKeyVault"keyVaultNamespace := keyVaultDBName + "." + keyVaultCollName// The Client used to read/write application data.client, err := Connect(context.TODO(),options.Client().ApplyURI("mongodb://localhost:27017"))if err != nil {panic(err)}defer func() { _ = client.Disconnect(context.TODO()) }()// Get a handle to the application collection and clear existing data.coll := client.Database("test").Collection("coll")_ = coll.Drop(context.TODO())// Set up the key vault for this example.keyVaultColl := client.Database(keyVaultDBName).Collection(keyVaultCollName)_ = keyVaultColl.Drop(context.TODO())// Ensure that two data keys cannot share the same keyAltName.keyVaultIndex := IndexModel{Keys: bson.D{{"keyAltNames", 1}},Options: options.Index().SetUnique(true).SetPartialFilterExpression(bson.D{{"keyAltNames", bson.D{{"$exists", true},}},}),}_, err = keyVaultColl.Indexes().CreateOne(context.TODO(), keyVaultIndex)if err != nil {panic(err)}// Create the ClientEncryption object to use for explicit// encryption/decryption. The Client passed to NewClientEncryption is used// to read/write to the key vault. This can be the same Client used by the// main application.clientEncryptionOpts := options.ClientEncryption().SetKmsProviders(kmsProviders).SetKeyVaultNamespace(keyVaultNamespace)clientEncryption, err := NewClientEncryption(client, clientEncryptionOpts)if err != nil {panic(err)}defer func() { _ = clientEncryption.Close(context.TODO()) }()// Create a new data key for the encrypted field.dataKeyOpts := options.DataKey().SetKeyAltNames([]string{"go_encryption_example"})dataKeyID, err := clientEncryption.CreateDataKey(context.TODO(),"local",dataKeyOpts)if err != nil {panic(err)}// Create a bson.RawValue to encrypt and encrypt it using the key that was// just created.rawValueType, rawValueData, err := bson.MarshalValue("123456789")if err != nil {panic(err)}rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData}encryptionOpts := options.Encrypt().SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").SetKeyID(dataKeyID)encryptedField, err := clientEncryption.Encrypt(context.TODO(),rawValue,encryptionOpts)if err != nil {panic(err)}// Insert a document with the encrypted field and then find it._, err = coll.InsertOne(context.TODO(),bson.D{{"encryptedField", encryptedField}})if err != nil {panic(err)}var foundDoc bson.Merr = coll.FindOne(context.TODO(), bson.D{}).Decode(&foundDoc)if err != nil {panic(err)}// Decrypt the encrypted field in the found document.decrypted, err := clientEncryption.Decrypt(context.TODO(),foundDoc["encryptedField"].(primitive.Binary))if err != nil {panic(err)}fmt.Printf("Decrypted value: %s\n", decrypted)Example (ExplictEncryptionWithAutomaticDecryption)¶
// Automatic encryption requires MongoDB 4.2 enterprise, but automatic// decryption is supported for all users.// localMasterKey must be the same master key that was used to create the// encryption key.var localMasterKey []bytekmsProviders := map[string]map[string]interface{}{"local": {"key": localMasterKey,},}// The MongoDB namespace (db.collection) used to store the encryption data// keys.keyVaultDBName, keyVaultCollName := "encryption", "testKeyVault"keyVaultNamespace := keyVaultDBName + "." + keyVaultCollName// Create the Client for reading/writing application data. Configure it with// BypassAutoEncryption=true to disable automatic encryption but keep// automatic decryption. Setting BypassAutoEncryption will also bypass// spawning mongocryptd in the driver.autoEncryptionOpts := options.AutoEncryption().SetKmsProviders(kmsProviders).SetKeyVaultNamespace(keyVaultNamespace).SetBypassAutoEncryption(true)clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAutoEncryptionOptions(autoEncryptionOpts)client, err := Connect(context.TODO(), clientOpts)if err != nil {panic(err)}defer func() { _ = client.Disconnect(context.TODO()) }()// Get a handle to the application collection and clear existing data.coll := client.Database("test").Collection("coll")_ = coll.Drop(context.TODO())// Set up the key vault for this example.keyVaultColl := client.Database(keyVaultDBName).Collection(keyVaultCollName)_ = keyVaultColl.Drop(context.TODO())// Ensure that two data keys cannot share the same keyAltName.keyVaultIndex := IndexModel{Keys: bson.D{{"keyAltNames", 1}},Options: options.Index().SetUnique(true).SetPartialFilterExpression(bson.D{{"keyAltNames", bson.D{{"$exists", true},}},}),}_, err = keyVaultColl.Indexes().CreateOne(context.TODO(), keyVaultIndex)if err != nil {panic(err)}// Create the ClientEncryption object to use for explicit// encryption/decryption. The Client passed to NewClientEncryption is used// to read/write to the key vault. This can be the same Client used by the// main application.clientEncryptionOpts := options.ClientEncryption().SetKmsProviders(kmsProviders).SetKeyVaultNamespace(keyVaultNamespace)clientEncryption, err := NewClientEncryption(client, clientEncryptionOpts)if err != nil {panic(err)}defer func() { _ = clientEncryption.Close(context.TODO()) }()// Create a new data key for the encrypted field.dataKeyOpts := options.DataKey().SetKeyAltNames([]string{"go_encryption_example"})dataKeyID, err := clientEncryption.CreateDataKey(context.TODO(),"local",dataKeyOpts)if err != nil {panic(err)}// Create a bson.RawValue to encrypt and encrypt it using the key that was// just created.rawValueType, rawValueData, err := bson.MarshalValue("123456789")if err != nil {panic(err)}rawValue := bson.RawValue{Type: rawValueType, Value: rawValueData}encryptionOpts := options.Encrypt().SetAlgorithm("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").SetKeyID(dataKeyID)encryptedField, err := clientEncryption.Encrypt(context.TODO(),rawValue,encryptionOpts)if err != nil {panic(err)}// Insert a document with the encrypted field and then find it. The FindOne// call will automatically decrypt the field in the document._, err = coll.InsertOne(context.TODO(),bson.D{{"encryptedField", encryptedField}})if err != nil {panic(err)}var foundDoc bson.Merr = coll.FindOne(context.TODO(), bson.D{}).Decode(&foundDoc)if err != nil {panic(err)}fmt.Printf("Decrypted document: %v\n", foundDoc)Index¶
- Variables
- func BatchCursorFromCursor(c *Cursor) *driver.BatchCursordeprecated
- func IsDuplicateKeyError(err error) bool
- func IsNetworkError(err error) bool
- func IsTimeout(err error) bool
- func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error
- type BSONAppenderdeprecated
- type BSONAppenderFuncdeprecated
- type BulkWriteError
- type BulkWriteException
- func (bwe BulkWriteException) Error() string
- func (bwe BulkWriteException) HasErrorCode(code int) bool
- func (bwe BulkWriteException) HasErrorCodeWithMessage(code int, message string) bool
- func (bwe BulkWriteException) HasErrorLabel(label string) bool
- func (bwe BulkWriteException) HasErrorMessage(message string) bool
- type BulkWriteResult
- type ChangeStream
- func (cs *ChangeStream) Close(ctx context.Context) error
- func (cs *ChangeStream) Decode(val interface{}) error
- func (cs *ChangeStream) Err() error
- func (cs *ChangeStream) ID() int64
- func (cs *ChangeStream) Next(ctx context.Context) bool
- func (cs *ChangeStream) RemainingBatchLength() int
- func (cs *ChangeStream) ResumeToken() bson.Raw
- func (cs *ChangeStream) SetBatchSize(size int32)
- func (cs *ChangeStream) TryNext(ctx context.Context) bool
- type Client
- func (c *Client) Connect(ctx context.Context) errordeprecated
- func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
- func (c *Client) Disconnect(ctx context.Context) error
- func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error)
- func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult, error)
- func (c *Client) NumberSessionsInProgress() int
- func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error
- func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)
- func (c *Client) Timeout() *time.Duration
- func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error
- func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, ...) error
- func (c *Client) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- type ClientEncryption
- func (ce *ClientEncryption) AddKeyAltName(ctx context.Context, id primitive.Binary, keyAltName string) *SingleResult
- func (ce *ClientEncryption) Close(ctx context.Context) error
- func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider string, opts ...*options.DataKeyOptions) (primitive.Binary, error)
- func (ce *ClientEncryption) CreateEncryptedCollection(ctx context.Context, db *Database, coll string, ...) (*Collection, bson.M, error)
- func (ce *ClientEncryption) Decrypt(ctx context.Context, val primitive.Binary) (bson.RawValue, error)
- func (ce *ClientEncryption) DeleteKey(ctx context.Context, id primitive.Binary) (*DeleteResult, error)
- func (ce *ClientEncryption) Encrypt(ctx context.Context, val bson.RawValue, opts ...*options.EncryptOptions) (primitive.Binary, error)
- func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr interface{}, result interface{}, ...) error
- func (ce *ClientEncryption) GetKey(ctx context.Context, id primitive.Binary) *SingleResult
- func (ce *ClientEncryption) GetKeyByAltName(ctx context.Context, keyAltName string) *SingleResult
- func (ce *ClientEncryption) GetKeys(ctx context.Context) (*Cursor, error)
- func (ce *ClientEncryption) RemoveKeyAltName(ctx context.Context, id primitive.Binary, keyAltName string) *SingleResult
- func (ce *ClientEncryption) RewrapManyDataKey(ctx context.Context, filter interface{}, ...) (*RewrapManyDataKeyResult, error)
- type Collection
- func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Cursor, error)
- func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, opts ...*options.BulkWriteOptions) (*BulkWriteResult, error)
- func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection, error)
- func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)
- func (coll *Collection) Database() *Database
- func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error)
- func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error)
- func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, ...) ([]interface{}, error)
- func (coll *Collection) Drop(ctx context.Context) error
- func (coll *Collection) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error)
- func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (cur *Cursor, err error)
- func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *SingleResult
- func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, ...) *SingleResult
- func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, ...) *SingleResult
- func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, ...) *SingleResult
- func (coll *Collection) Indexes() IndexView
- func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, ...) (*InsertManyResult, error)
- func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*InsertOneResult, error)
- func (coll *Collection) Name() string
- func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) SearchIndexes() SearchIndexView
- func (coll *Collection) UpdateByID(ctx context.Context, id interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- type CollectionSpecification
- type CommandError
- func (e CommandError) Error() string
- func (e CommandError) HasErrorCode(code int) bool
- func (e CommandError) HasErrorCodeWithMessage(code int, message string) bool
- func (e CommandError) HasErrorLabel(label string) bool
- func (e CommandError) HasErrorMessage(message string) bool
- func (e CommandError) IsMaxTimeMSExpiredError() bool
- func (e CommandError) Unwrap() error
- type Cursor
- func (c *Cursor) All(ctx context.Context, results interface{}) error
- func (c *Cursor) Close(ctx context.Context) error
- func (c *Cursor) Decode(val interface{}) error
- func (c *Cursor) Err() error
- func (c *Cursor) ID() int64
- func (c *Cursor) Next(ctx context.Context) bool
- func (c *Cursor) RemainingBatchLength() int
- func (c *Cursor) SetBatchSize(batchSize int32)
- func (c *Cursor) SetComment(comment interface{})
- func (c *Cursor) SetMaxTime(dur time.Duration)
- func (c *Cursor) TryNext(ctx context.Context) bool
- type Database
- func (db *Database) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Cursor, error)
- func (db *Database) Client() *Client
- func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection
- func (db *Database) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error
- func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{}, ...) error
- func (db *Database) Drop(ctx context.Context) error
- func (db *Database) ListCollectionNames(ctx context.Context, filter interface{}, ...) ([]string, error)
- func (db *Database) ListCollectionSpecifications(ctx context.Context, filter interface{}, ...) ([]*CollectionSpecification, error)
- func (db *Database) ListCollections(ctx context.Context, filter interface{}, ...) (*Cursor, error)
- func (db *Database) Name() string
- func (db *Database) ReadConcern() *readconcern.ReadConcern
- func (db *Database) ReadPreference() *readpref.ReadPref
- func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
- func (db *Database) RunCommandCursor(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor, error)
- func (db *Database) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- func (db *Database) WriteConcern() *writeconcern.WriteConcern
- type DatabaseSpecification
- type DeleteManyModel
- type DeleteOneModel
- type DeleteResult
- type Dialer
- type EncryptionKeyVaultError
- type ErrMapForOrderedArgument
- type IndexModel
- type IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Background(background bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Bits(bits int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) BucketSize(bucketSize int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Build() bson.Ddeprecated
- func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguage string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSeconds int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Max(max float64) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Name(name string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Sparse(sparse bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) SphereVersion(sphereVersion int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) TextVersion(textVersion int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Unique(unique bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Version(version int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilderdeprecated
- type IndexSpecification
- type IndexView
- func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, ...) ([]string, error)
- func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*options.CreateIndexesOptions) (string, error)
- func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOptions) (bson.Raw, error)
- func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.DropIndexesOptions) (bson.Raw, error)
- func (iv IndexView) DropOneWithKey(ctx context.Context, keySpecDocument interface{}, ...) (bson.Raw, error)
- func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (*Cursor, error)
- func (iv IndexView) ListSpecifications(ctx context.Context, opts ...*options.ListIndexesOptions) ([]*IndexSpecification, error)
- type InsertManyResult
- type InsertOneModel
- type InsertOneResult
- type LabeledError
- type ListDatabasesResult
- type MarshalError
- type MongocryptError
- type MongocryptdError
- type Pipeline
- type ReplaceOneModel
- func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel
- type RewrapManyDataKeyResult
- type SearchIndexModel
- type SearchIndexView
- func (siv SearchIndexView) CreateMany(ctx context.Context, models []SearchIndexModel, ...) ([]string, error)
- func (siv SearchIndexView) CreateOne(ctx context.Context, model SearchIndexModel, ...) (string, error)
- func (siv SearchIndexView) DropOne(ctx context.Context, name string, _ ...*options.DropSearchIndexOptions) error
- func (siv SearchIndexView) List(ctx context.Context, searchIdxOpts *options.SearchIndexesOptions, ...) (*Cursor, error)
- func (siv SearchIndexView) UpdateOne(ctx context.Context, name string, definition interface{}, ...) error
- type ServerError
- type Session
- type SessionContext
- type SingleResult
- type StreamType
- type UpdateManyModel
- func (umm *UpdateManyModel) SetArrayFilters(filters options.ArrayFilters) *UpdateManyModel
- func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel
- func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetUpsert(upsert bool) *UpdateManyModel
- type UpdateOneModel
- func (uom *UpdateOneModel) SetArrayFilters(filters options.ArrayFilters) *UpdateOneModel
- func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel
- func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel
- type UpdateResult
- type WriteConcernError
- type WriteError
- type WriteErrors
- type WriteException
- type WriteModel
- type XSessiondeprecated
- Bugs
Examples¶
- Package (ClientSideEncryption)
- Package (ClientSideEncryptionCreateKey)
- Package (ExplictEncryption)
- Package (ExplictEncryptionWithAutomaticDecryption)
- ChangeStream.Next
- ChangeStream.ResumeToken
- ChangeStream.TryNext
- Client
- Client.ListDatabaseNames
- Client.StartSession (WithTransaction)
- Client.UseSessionWithOptions
- Client.Watch
- Collection.Aggregate
- Collection.BulkWrite
- Collection.CountDocuments
- Collection.DeleteMany
- Collection.DeleteOne
- Collection.Distinct
- Collection.EstimatedDocumentCount
- Collection.Find
- Collection.Find (PrimitiveRegex)
- Collection.Find (Regex)
- Collection.FindOne
- Collection.FindOneAndDelete
- Collection.FindOneAndReplace
- Collection.FindOneAndUpdate
- Collection.InsertMany
- Collection.InsertOne
- Collection.ReplaceOne
- Collection.UpdateMany
- Collection.UpdateOne
- Collection.Watch
- Connect (AWS)
- Connect (BSONOptions)
- Connect (Direct)
- Connect (Kerberos)
- Connect (OIDC)
- Connect (PLAIN)
- Connect (Ping)
- Connect (ReplicaSet)
- Connect (SCRAM)
- Connect (SRV)
- Connect (Sharded)
- Connect (StableAPI)
- Connect (X509)
- Cursor.All
- Cursor.Next
- Cursor.RemainingBatchLength
- Cursor.TryNext
- Database.CreateCollection
- Database.CreateView
- Database.ListCollectionNames
- Database.RunCommand
- Database.Watch
- IndexView.CreateMany
- IndexView.List
- NewSessionContext
- WithSession
Constants¶
This section is empty.
Variables¶
var (// ErrMissingResumeToken indicates that a change stream notification from the server did not contain a resume token.ErrMissingResumeToken =errors.New("cannot provide resume functionality when the resume token is missing")// ErrNilCursor indicates that the underlying cursor for the change stream is nil.ErrNilCursor =errors.New("cursor is nil"))
var ErrClientDisconnected =errors.New("client is disconnected")ErrClientDisconnected is returned when disconnected Client is used to run an operation.
var ErrEmptySlice =errors.New("must provide at least one element in input slice")ErrEmptySlice is returned when an empty slice is passed to a CRUD method that requires a non-empty slice.
var ErrInvalidIndexValue =errors.New("invalid index value")ErrInvalidIndexValue is returned if an index is created with a keys document that has a value that is not a numberor string.
var ErrMultipleIndexDrop =errors.New("multiple indexes would be dropped")ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne.
var ErrNilDocument =errors.New("document is nil")ErrNilDocument is returned when a nil document is passed to a CRUD method.
var ErrNilValue =errors.New("value is nil")ErrNilValue is returned when a nil value is passed to a CRUD method.
var ErrNoDocuments =errors.New("mongo: no documents in result")ErrNoDocuments is returned by SingleResult methods when the operation that created the SingleResult did not returnany documents.
var ErrNonStringIndexName =errors.New("index name must be a string")ErrNonStringIndexName is returned if an index is created with a name that is not a string.
var ErrUnacknowledgedWrite =errors.New("unacknowledged write")ErrUnacknowledgedWrite is returned by operations that have an unacknowledged write concern.
var ErrWrongClient =errors.New("session was not created by this client")ErrWrongClient is returned when a user attempts to pass in a session created by a different client thanthe method call is using.
Functions¶
funcBatchCursorFromCursordeprecatedadded inv1.1.0
func BatchCursorFromCursor(c *Cursor) *driver.BatchCursor
BatchCursorFromCursor returns a driver.BatchCursor for the given Cursor. If there is no underlyingdriver.BatchCursor, nil is returned.
Deprecated: This is an unstable function because the driver.BatchCursor type exists in the "x" package. Neither thisfunction nor the driver.BatchCursor type should be used by applications and may be changed or removed in any release.
funcIsDuplicateKeyError¶added inv1.5.0
IsDuplicateKeyError returns true if err is a duplicate key error.
funcIsNetworkError¶added inv1.5.0
IsNetworkError returns true if err is a network error
funcIsTimeout¶added inv1.5.0
IsTimeout returns true if err was caused by a timeout. For error chains,IsTimeout returns true if any error in the chain was caused by a timeout.
funcWithSession¶added inv0.0.16
WithSession creates a new SessionContext from the ctx and sess parameters and uses it to call the fn callback. TheSessionContext must be used as the Context parameter for any operations in the fn callback that should be executedunder the session.
WithSession is safe to call from multiple goroutines concurrently. However, the SessionContext passed to theWithSession callback function is not safe for concurrent use by multiple goroutines.
If the ctx parameter already contains a Session, that Session will be replaced with the one provided.
Any error returned by the fn callback will be returned without any modifications.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readconcern")func main() {// Assume client is configured with write concern majority and read// preference primary.var client *mongo.Client// Specify the DefaultReadConcern option so any transactions started through// the session will have read concern majority.// The DefaultReadPreference and DefaultWriteConcern options aren't// specified so they will be inheritied from client and be set to primary// and majority, respectively.opts := options.Session().SetDefaultReadConcern(readconcern.Majority())sess, err := client.StartSession(opts)if err != nil {log.Panic(err)}defer sess.EndSession(context.TODO())// Call WithSession to start a transaction within the new session.err = mongo.WithSession(context.TODO(),sess,func(ctx mongo.SessionContext) error {// Use the mongo.SessionContext as the Context parameter for// InsertOne and FindOne so both operations are run under the new// Session.if err := sess.StartTransaction(); err != nil {return err}coll := client.Database("db").Collection("coll")res, err := coll.InsertOne(ctx, bson.D{{"x", 1}})if err != nil {// Abort the transaction after an error. Use// context.Background() to ensure that the abort can complete// successfully even if the context passed to mongo.WithSession// is changed to have a timeout._ = sess.AbortTransaction(context.Background())return err}var result bson.Merr = coll.FindOne(ctx,bson.D{{"_id", res.InsertedID}},).Decode(result)if err != nil {// Abort the transaction after an error. Use// context.Background() to ensure that the abort can complete// successfully even if the context passed to mongo.WithSession// is changed to have a timeout._ = sess.AbortTransaction(context.Background())return err}fmt.Println(result)// Use context.Background() to ensure that the commit can complete// successfully even if the context passed to mongo.WithSession is// changed to have a timeout.return sess.CommitTransaction(context.Background())})if err != nil {log.Panic(err)}}Types¶
typeBSONAppenderdeprecatedadded inv0.0.15
BSONAppender is an interface implemented by types that can marshal aprovided type into BSON bytes and append those bytes to the provided []byte.The AppendBSON can return a non-nil error and non-nil []byte. The AppendBSONmethod may also write incomplete BSON to the []byte.
Deprecated: BSONAppender is unused and will be removed in Go Driver 2.0.
typeBSONAppenderFuncdeprecatedadded inv0.0.15
BSONAppenderFunc is an adapter function that allows any function thatsatisfies the AppendBSON method signature to be used where a BSONAppender isused.
Deprecated: BSONAppenderFunc is unused and will be removed in Go Driver 2.0.
func (BSONAppenderFunc)AppendBSONdeprecatedadded inv0.0.15
func (bafBSONAppenderFunc) AppendBSON(dst []byte, val interface{}) ([]byte,error)
AppendBSON implements the BSONAppender interface
Deprecated: BSONAppenderFunc is unused and will be removed in Go Driver 2.0.
typeBulkWriteError¶added inv0.0.4
type BulkWriteError struct {WriteError// The WriteError that occurred.RequestWriteModel// The WriteModel that caused this error.}BulkWriteError is an error that occurred during execution of one operation in a BulkWrite. This error type is onlyreturned as part of a BulkWriteException.
func (BulkWriteError)Error¶added inv0.0.4
func (bweBulkWriteError) Error()string
Error implements the error interface.
typeBulkWriteException¶added inv0.0.16
type BulkWriteException struct {// The write concern error that occurred, or nil if there was none.WriteConcernError *WriteConcernError// The write errors that occurred during operation execution.WriteErrors []BulkWriteError// The categories to which the exception belongs.Labels []string}BulkWriteException is the error type returned by BulkWrite and InsertMany operations.
func (BulkWriteException)Error¶added inv0.0.16
func (bweBulkWriteException) Error()string
Error implements the error interface.
func (BulkWriteException)HasErrorCode¶added inv1.5.0
func (bweBulkWriteException) HasErrorCode(codeint)bool
HasErrorCode returns true if any of the errors have the specified code.
func (BulkWriteException)HasErrorCodeWithMessage¶added inv1.5.0
func (bweBulkWriteException) HasErrorCodeWithMessage(codeint, messagestring)bool
HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message.
func (BulkWriteException)HasErrorLabel¶added inv1.4.0
func (bweBulkWriteException) HasErrorLabel(labelstring)bool
HasErrorLabel returns true if the error contains the specified label.
func (BulkWriteException)HasErrorMessage¶added inv1.5.0
func (bweBulkWriteException) HasErrorMessage(messagestring)bool
HasErrorMessage returns true if the error contains the specified message.
typeBulkWriteResult¶added inv0.0.16
type BulkWriteResult struct {// The number of documents inserted.InsertedCountint64// The number of documents matched by filters in update and replace operations.MatchedCountint64// The number of documents modified by update and replace operations.ModifiedCountint64// The number of documents deleted.DeletedCountint64// The number of documents upserted by update and replace operations.UpsertedCountint64// A map of operation index to the _id of each upserted document.UpsertedIDs map[int64]interface{}}BulkWriteResult is the result type returned by a BulkWrite operation.
typeChangeStream¶added inv0.3.0
type ChangeStream struct {// Current is the BSON bytes of the current event. This property is only valid until the next call to Next or// TryNext. If continued access is required, a copy must be made.Currentbson.Raw// contains filtered or unexported fields}ChangeStream is used to iterate over a stream of events. Each event can be decoded into a Go type via the Decodemethod or accessed as raw BSON via the Current field. This type is not goroutine safe and must not be usedconcurrently by multiple goroutines. For more information about change streams, seehttps://www.mongodb.com/docs/manual/changeStreams/.
func (*ChangeStream)Close¶added inv0.3.0
func (cs *ChangeStream) Close(ctxcontext.Context)error
Close closes this change stream and the underlying cursor. Next and TryNext must not be called after Close has beencalled. Close is idempotent. After the first call, any subsequent calls will not change the state.
func (*ChangeStream)Decode¶added inv0.3.0
func (cs *ChangeStream) Decode(val interface{})error
Decode will unmarshal the current event document into val and return any errors from the unmarshalling processwithout any modification. If val is nil or is a typed nil, an error will be returned.
func (*ChangeStream)Err¶added inv0.3.0
func (cs *ChangeStream) Err()error
Err returns the last error seen by the change stream, or nil if no errors has occurred.
func (*ChangeStream)ID¶added inv0.3.0
func (cs *ChangeStream) ID()int64
ID returns the ID for this change stream, or 0 if the cursor has been closed or exhausted.
func (*ChangeStream)Next¶added inv0.3.0
func (cs *ChangeStream) Next(ctxcontext.Context)bool
Next gets the next event for this change stream. It returns true if there were no errors and the next event documentis available.
Next blocks until an event is available, an error occurs, or ctx expires. If ctx expires, the errorwill be set to ctx.Err(). In an error case, Next will return false.
If Next returns false, subsequent calls will also return false.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var stream *mongo.ChangeStreamdefer stream.Close(context.TODO())// Iterate the change stream and print out each event.// Because the Next call blocks until an event is available, another way to// iterate the change stream is to call Next in a goroutine and pass in a// context that can be cancelled to abort the call.for stream.Next(context.TODO()) {// A new event variable should be declared for each event.var event bson.Mif err := stream.Decode(&event); err != nil {log.Panic(err)}fmt.Println(event)}if err := stream.Err(); err != nil {log.Panic(err)}}func (*ChangeStream)RemainingBatchLength¶added inv1.15.1
func (cs *ChangeStream) RemainingBatchLength()int
RemainingBatchLength returns the number of documents left in the current batch. If this returns zero, the subsequentcall to Next or TryNext will do a network request to fetch the next batch.
func (*ChangeStream)ResumeToken¶added inv1.1.0
func (cs *ChangeStream) ResumeToken()bson.Raw
ResumeToken returns the last cached resume token for this change stream, or nil if a resume token has not beenstored.
Example¶
package mainimport ("context""fmt""log""sync""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var client *mongo.Client// Assume stream was created via client.Watch()var stream *mongo.ChangeStreamcancelCtx, cancel := context.WithCancel(context.TODO())defer cancel()var wg sync.WaitGroupwg.Add(1)// Run a goroutine to process events.go func() {for stream.Next(cancelCtx) {fmt.Println(stream.Current)}wg.Done()}()// Assume client needs to be disconnected. Cancel the context being used by// the goroutine to abort any in-progres Next calls and wait for the// goroutine to exit.cancel()wg.Wait()// Before disconnecting the client, store the last seen resume token for the// change stream.resumeToken := stream.ResumeToken()_ = client.Disconnect(context.TODO())// Once a new client is created, the change stream can be re-created.// Specify resumeToken as the ResumeAfter option so only events that// occurred after resumeToken will be returned.var newClient *mongo.Clientopts := options.ChangeStream().SetResumeAfter(resumeToken)newStream, err := newClient.Watch(context.TODO(), mongo.Pipeline{}, opts)if err != nil {log.Panic(err)}defer newStream.Close(context.TODO())}func (*ChangeStream)SetBatchSize¶added inv1.11.9
func (cs *ChangeStream) SetBatchSize(sizeint32)
SetBatchSize sets the number of documents to fetch from the database witheach iteration of the ChangeStream's "Next" or "TryNext" method. This settingonly affects subsequent document batches fetched from the database.
func (*ChangeStream)TryNext¶added inv1.2.0
func (cs *ChangeStream) TryNext(ctxcontext.Context)bool
TryNext attempts to get the next event for this change stream. It returns true if there were no errors and the nextevent document is available.
TryNext returns false if the change stream is closed by the server, an error occurs when getting changes from theserver, the next change is not yet available, or ctx expires. If ctx expires, the error will be set to ctx.Err().
If TryNext returns false and an error occurred or the change stream was closed(i.e. cs.Err() != nil || cs.ID() == 0), subsequent attempts will also return false. Otherwise, it is safe to callTryNext again until a change is available.
This method requires driver version >= 1.2.0.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var stream *mongo.ChangeStreamdefer stream.Close(context.TODO())// Iterate the change stream and print out each event until the change// stream is closed by the server or there is an error getting the next// event.for {if stream.TryNext(context.TODO()) {// A new event variable should be declared for each event.var event bson.Mif err := stream.Decode(&event); err != nil {log.Panic(err)}fmt.Println(event)continue}// If TryNext returns false, the next change is not yet available, the// change stream was closed by the server, or an error occurred. TryNext// should only be called again for the empty batch case.if err := stream.Err(); err != nil {log.Panic(err)}if stream.ID() == 0 {break}}}typeClient¶
type Client struct {// contains filtered or unexported fields}Client is a handle representing a pool of connections to a MongoDB deployment. It is safe for concurrent use bymultiple goroutines.
The Client type opens and closes connections automatically and maintains a pool of idle connections. Forconnection pool configuration options, see documentation for the ClientOptions type in the mongo/options package.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Create a Client and execute a ListDatabases operation.client, err := mongo.Connect(context.TODO(),options.Client().ApplyURI("mongodb://localhost:27017"))if err != nil {log.Panic(err)}defer func() {if err = client.Disconnect(context.TODO()); err != nil {log.Panic(err)}}()collection := client.Database("db").Collection("coll")result, err := collection.InsertOne(context.TODO(), bson.D{{"x", 1}})if err != nil {log.Panic(err)}fmt.Printf("inserted ID: %v\n", result.InsertedID)}funcConnect¶added inv0.0.3
Connect creates a new Client and then initializes it using the Connect method. This is equivalent to callingNewClient followed by Client.Connect.
When creating an options.ClientOptions, the order the methods are called matters. Later Set*methods will overwrite the values from previous Set* method invocations. This includes theApplyURI method. This allows callers to determine the order of precedence for optionapplication. For instance, if ApplyURI is called before SetAuth, the Credential fromSetAuth will overwrite the values from the connection string. If ApplyURI is calledafter SetAuth, then its values will overwrite those from SetAuth.
The opts parameter is processed using options.MergeClientOptions, which will overwrite entireoption fields of previous options, there is no partial overwriting. For example, if Username isset in the Auth field for the first option, and Password is set for the second but with noUsername, after the merge the Username field will be empty.
The NewClient function does not do any I/O and returns an error if the given options are invalid.The Client.Connect method starts background goroutines to monitor the state of the deployment and does not doany I/O in the main goroutine to prevent the main goroutine from blocking. Therefore, it will not error if thedeployment is down.
The Client.Ping method can be used to verify that the deployment is successfully connected and theClient was correctly configured.
Example (AWS)¶
package mainimport ("context""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with authentication using the MONGODB-AWS// authentication mechanism. Credentials for this mechanism can come from// one of four sources://// 1. AWS IAM credentials (an access key ID and a secret access key)//// 2. Temporary AWS IAM credentials// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)// obtained from an AWS Security Token Service (STS) Assume Role request// (https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)//// 3. AWS Lambda environment variables// (https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime)//// 4. Temporary AWS IAM credentials assigned to an EC2 instance or ECS task// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)// The order in which the driver searches for credentials is://// 1. Credentials passed through the URI// 2. Environment variables// 3. ECS endpoint if and only if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is// set// 4. EC2 endpoint//// The following examples set the appropriate credentials via the// ClientOptions.SetAuth method. All of these credentials can be specified// via the ClientOptions.ApplyURI method as well. If using ApplyURI, both// the username and password must be URL encoded (see net.URL.QueryEscape())// AWS IAM Credentials// Applications can authenticate using AWS IAM credentials by providing a// valid access key ID and secret access key pair as the username and// password, respectively.var accessKeyID, secretAccessKey stringawsCredential := options.Credential{AuthMechanism: "MONGODB-AWS",Username: accessKeyID,Password: secretAccessKey,}awsIAMClient, err := mongo.Connect(context.TODO(),options.Client().SetAuth(awsCredential))if err != nil {panic(err)}_ = awsIAMClient// AssumeRole// Applications can authenticate using temporary credentials returned from// an assume role request. These temporary credentials consist of an access// key ID, a secret access key, and a security token.var sessionToken stringassumeRoleCredential := options.Credential{AuthMechanism: "MONGODB-AWS",Username: accessKeyID,Password: secretAccessKey,AuthMechanismProperties: map[string]string{"AWS_SESSION_TOKEN": sessionToken,},}assumeRoleClient, err := mongo.Connect(context.TODO(),options.Client().SetAuth(assumeRoleCredential))if err != nil {panic(err)}_ = assumeRoleClient// AWS Lambda (Environment Variables)// When the username and password are not provided and the MONGODB-AWS// mechanism is set, the client will fallback to using the environment// variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN// for the access key ID, secret access key, and session token,// respectively. These environment variables must not be URL encoded.// $ export AWS_ACCESS_KEY_ID=<accessKeyID>// $ export AWS_SECRET_ACCESS_KEY=<secretAccessKey>// $ export AWS_SESSION_TOKEN=<sessionToken>envVariablesCredential := options.Credential{AuthMechanism: "MONGODB-AWS",}envVariablesClient, err := mongo.Connect(context.TODO(),options.Client().SetAuth(envVariablesCredential))if err != nil {panic(err)}_ = envVariablesClient// ECS Container or EC2 Instance// Applications can authenticate from an ECS container or EC2 instance via// temporary credentials assigned to the machine. If using an ECS container,// the "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" environment variable must be// set to a non-empty value. The driver will query the ECS or EC2 endpoint// to obtain the relevant credentials.ecCredential := options.Credential{AuthMechanism: "MONGODB-AWS",}ecClient, err := mongo.Connect(context.TODO(),options.Client().SetAuth(ecCredential))if err != nil {panic(err)}_ = ecClient}Example (BSONOptions)¶
package mainimport ("context""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a client that customizes the BSON marshal and unmarshal// behavior.// Specify BSON options that cause the driver to fallback to "json"// struct tags if "bson" struct tags are missing, marshal nil Go maps as// empty BSON documents, and marshals nil Go slices as empty BSON// arrays.bsonOpts := &options.BSONOptions{UseJSONStructTags: true,NilMapAsEmpty: true,NilSliceAsEmpty: true,}clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetBSONOptions(bsonOpts)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {panic(err)}defer func() {if err := client.Disconnect(context.TODO()); err != nil {panic(err)}}()coll := client.Database("db").Collection("coll")// Define a struct that contains a map and a slice and uses "json" struct// tags to specify field names.type myDocument struct {MyMap map[string]interface{} `json:"a"`MySlice []string `json:"b"`}// Insert an instance of the struct with all empty fields. Expect the// resulting BSON document to have a structure like {"a": {}, "b": []}_, err = coll.InsertOne(context.TODO(), myDocument{})if err != nil {panic(err)}}Example (Direct)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Create a direct connection to a host. The driver will send all requests// to that host and will not automatically discover other hosts in the// deployment.clientOpts := options.Client().ApplyURI("mongodb://localhost:27017/?connect=direct")client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (Kerberos)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with GSSAPI/SSPI authentication (https://www.mongodb.com/docs/manual/core/kerberos/).// MongoDB Enterprise supports proxy authentication through a Kerberos// service. Using Kerberos authentication requires the "gssapi" build tag// and cgo support during compilation. The default service name for Kerberos// is "mongodb". This can be configured via the AuthMechanismProperties// field in the options.Credential struct or the authMechanismProperties URI// parameter.// For Linux, the libkrb5 library is required.// Users can authenticate in one of two ways:// 1. Use an explicit password. In this case, a password must be specified// in the URI or the options.Credential struct and no further setup is// required.// 2. Store authentication keys in keytab files. To do this, the kinit// binary should be used to initialize a credential cache for authenticating// the user principal. In this example, the invocation would be// "kinit drivers@KERBEROS.EXAMPLE.COM".// To configure auth via a URI instead of a Credential, use// "mongodb://drivers%40KERBEROS.EXAMPLE.COM@mongo-server.example.com:27017/?authMechanism=GSSAPI".credential := options.Credential{AuthMechanism: "GSSAPI",Username: "drivers@KERBEROS.EXAMPLE.COM",}uri := "mongo-server.example.com:27017"clientOpts := options.Client().ApplyURI(uri).SetAuth(credential)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (OIDC)¶
package mainimport ("context""os""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// The `MONGODB-OIDC authentication mechanism` is available in MongoDB 7.0+// on Linux platforms.//// The MONGODB-OIDC mechanism authenticates using an OpenID Connect (OIDC)// access token. The driver supports OIDC for workload identity, defined as// an identity you assign to a software workload (such as an application,// service, script, or container) to authenticate and access other services// and resources.//// The driver also supports OIDC for workforce identity for a more secure// flow with a human in the loop.// Credentials can be configured through the MongoDB URI or as arguments in// the options.ClientOptions struct that is passed into the mongo.Connect// function.// Built-in Support// The driver has built-in support for Azure IMDS and GCP// IMDS environments. Other environments are supported with `Custom// Callbacks`.// Azure IMDS// For an application running on an Azure VM or otherwise using the `Azure// Internal Metadata Service`, you can use the built-in support for Azure,// where "<client_id>" below is the client id of the Azure managed identity,// and ``<audience>`` is the url-encoded ``audience`` `configured on your// MongoDB deployment`.{uri := os.Getenv("MONGODB_URI")props := map[string]string{"ENVIRONMENT": "azure","TOKEN_RESOURCE": "<audience>",}opts := options.Client().ApplyURI(uri)opts.SetAuth(options.Credential{Username: "<client_id>",AuthMechanism: "MONGODB-OIDC",AuthMechanismProperties: props,},)c, err := mongo.Connect(context.TODO(), opts)if err != nil {panic(err)}defer func() { _ = c.Disconnect(context.TODO()) }()_, err = c.Database("test").Collection("test").InsertOne(context.TODO(), bson.D{})if err != nil {panic(err)}}// If the application is running on an Azure VM and only one managed// identity is associated with the VM, "username" can be omitted.// GCP IMDS// For an application running on an GCP VM or otherwise using the `GCP// Internal Metadata Service`_, you can use the built-in support for GCP,// where "<audience>" below is the url-encoded "audience" `configured on// your MongoDB deployment`.{uri := os.Getenv("MONGODB_URI")props := map[string]string{"ENVIRONMENT": "gcp","TOKEN_RESOURCE": "<audience>",}opts := options.Client().ApplyURI(uri)opts.SetAuth(options.Credential{AuthMechanism: "MONGODB-OIDC",AuthMechanismProperties: props,},)c, err := mongo.Connect(context.TODO(), opts)if err != nil {panic(err)}defer func() { _ = c.Disconnect(context.TODO()) }()_, err = c.Database("test").Collection("test").InsertOne(context.TODO(), bson.D{})if err != nil {panic(err)}}// Custom Callbacks// For environments that are not directly supported by the driver, you can// use options.OIDCCallback. Some examples are given below.// AWS EKS// For an EKS Cluster with a configured `IAM OIDC provider`, the token can// be read from a path given by the "AWS_WEB_IDENTITY_TOKEN_FILE"// environment variable.{eksCallback := func(_ context.Context,_ *options.OIDCArgs) (*options.OIDCCredential, error) {accessToken, err := os.ReadFile(os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"))if err != nil {return nil, err}return &options.OIDCCredential{AccessToken: string(accessToken),}, nil}uri := os.Getenv("MONGODB_URI")opts := options.Client().ApplyURI(uri)opts.SetAuth(options.Credential{AuthMechanism: "MONGODB-OIDC",OIDCMachineCallback: eksCallback,},)c, err := mongo.Connect(context.TODO(), opts)if err != nil {panic(err)}defer func() { _ = c.Disconnect(context.TODO()) }()_, err = c.Database("test").Collection("test").InsertOne(context.TODO(), bson.D{})if err != nil {panic(err)}}// Other Azure Environments// For applications running on Azure Functions, App Service Environment// (ASE), or Azure Kubernetes Service (AKS), you can use the `azidentity// package`// (https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) to// fetch the credentials. In each case, the OIDCCallback function should// return the AccessToken from the azidentity package.// GCP GKE// For a Google Kubernetes Engine cluster with a `configured service// account`, the token can be read from the standard service account token// file location.{gkeCallback := func(_ context.Context,_ *options.OIDCArgs) (*options.OIDCCredential, error) {accessToken, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")if err != nil {return nil, err}return &options.OIDCCredential{AccessToken: string(accessToken),}, nil}uri := os.Getenv("MONGODB_URI")props := map[string]string{"ENVIRONMENT": "gcp","TOKEN_RESOURCE": "<audience>",}opts := options.Client().ApplyURI(uri)opts.SetAuth(options.Credential{AuthMechanism: "MONGODB-OIDC",AuthMechanismProperties: props,OIDCMachineCallback: gkeCallback,},)c, err := mongo.Connect(context.TODO(), opts)if err != nil {panic(err)}defer func() { _ = c.Disconnect(context.TODO()) }()_, err = c.Database("test").Collection("test").InsertOne(context.TODO(), bson.D{})if err != nil {panic(err)}}// For workforce identity, the Client must be configured with the// OIDCHumanCallback rather than the OIDCMachineCallback. The// OIDCHumanCallback is used by the driver in a process that is two step. In// the first step, the driver retrieves the Identity Provider (IDP)// Information (IDPInfo) for the passed username. The OIDCHumanCallback then// needs to negotiate with the IDP in order to obtain an AccessToken,// possible RefreshToken, any timeouts, and return them, similar to the// OIDCMachineCallbacks seen above. See// https://docs.hidglobal.com/dev/auth-service/integration/openid-authentication-flows.html// for more information on various OIDC authentication flows.{humanCallback := func(ctx context.Context,opts *options.OIDCArgs) (*options.OIDCCredential, error) {// idpInfo passed from the driver by asking the MongoDB server for// the info configured for the usernameidpInfo := opts.IDPInfo// negotiateWithIDP must work with the IdP to obtain an access// token. In many cases this will involve opening a webbrowser or// providing a URL on the command line to a human-in-the-loop who// can give permissions to the IdP.accessToken, err := negotiateWithIDP(ctx, idpInfo.Issuer)if err != nil {return nil, err}return &options.OIDCCredential{AccessToken: accessToken,}, nil}uri := os.Getenv("MONGODB_URI")props := map[string]string{"ENVIRONMENT": "gcp","TOKEN_RESOURCE": "<audience>",}opts := options.Client().ApplyURI(uri)opts.SetAuth(options.Credential{AuthMechanism: "MONGODB-OIDC",AuthMechanismProperties: props,OIDCHumanCallback: humanCallback,},)c, err := mongo.Connect(context.TODO(), opts)if err != nil {panic(err)}defer func() { _ = c.Disconnect(context.TODO()) }()_, err = c.Database("test").Collection("test").InsertOne(context.TODO(), bson.D{})if err != nil {panic(err)}}// * MONGODB-OIDC authentication mechanism:// https://www.mongodb.com/docs/manual/core/security-oidc/// * OIDC Identity Provider Configuration:// https://www.mongodb.com/docs/manual/reference/parameters/#mongodb-parameter-param.oidcIdentityProviders// * Azure Internal Metadata Service:// https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service// * GCP Internal Metadata Service:// https://cloud.google.com/compute/docs/metadata/querying-metadata// * IAM OIDC provider:// https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html// * azure-identity package:// https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity// * configured service account:// https://cloud.google.com/kubernetes-engine/docs/how-to/service-accounts}func negotiateWithIDP(_ context.Context, _ string) (string, error) {return "", nil}Example (PLAIN)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with LDAP authentication// (https://www.mongodb.com/docs/manual/core/authentication-mechanisms-enterprise/#security-auth-ldap).// MongoDB Enterprise supports proxy authentication through an LDAP service// that can be used through the PLAIN authentication mechanism.// This auth mechanism sends the password in plaintext and therefore should// only be used with TLS connections.// To configure auth via a URI instead of a Credential, use// "mongodb://ldap-user:ldap-pwd@localhost:27017/?authMechanism=PLAIN".credential := options.Credential{AuthMechanism: "PLAIN",Username: "ldap-user",Password: "ldap-pwd",}clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (Ping)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readpref")func main() {// Create a Client to a MongoDB server and use Ping to verify that the// server is running.clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}defer func() {if err = client.Disconnect(context.TODO()); err != nil {log.Panic(err)}}()// Call Ping to verify that the deployment is up and the Client was// configured successfully. As mentioned in the Ping documentation, this// reduces application resiliency as the server may be temporarily// unavailable when Ping is called.if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {log.Panic(err)}}Example (ReplicaSet)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Create and connect a Client to a replica set deployment.// Given this URI, the Go driver will first communicate with localhost:27017// and use the response to discover any other members in the replica set.// The URI in this example specifies multiple members of the replica set to// increase resiliency as one of the members may be down when the// application is started.clientOpts := options.Client().ApplyURI("mongodb://localhost:27017,localhost:27018/?replicaSet=replset")client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (SCRAM)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with SCRAM authentication// (https://www.mongodb.com/docs/manual/core/security-scram/).// The default authentication database for SCRAM is "admin". This can be// configured via the authSource query parameter in the URI or the// AuthSource field in the options.Credential struct. SCRAM is the default// auth mechanism so specifying a mechanism is not required.// To configure auth via URI instead of a Credential, use// "mongodb://user:password@localhost:27017".credential := options.Credential{Username: "user",Password: "password",}clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (SRV)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Create and connect a Client using an SRV record.// SRV records allow administrators to configure a single domain to return a// list of host names. The driver will resolve SRV records prefixed with// "_mongodb_tcp" and use the returned host names to build its view of the// deployment.// See https://www.mongodb.com/docs/manual/reference/connection-string/ for more// information about SRV. Full support for SRV records with sharded clusters// requires driver version 1.1.0 or higher.clientOpts := options.Client().ApplyURI("mongodb+srv://mongodb.example.com")client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (Sharded)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Create and connect a Client to a sharded deployment.// The URI for a sharded deployment should specify the mongos servers that// the application wants to send messages to.clientOpts := options.Client().ApplyURI("mongodb://localhost:27017,localhost:27018")client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client}Example (StableAPI)¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with stable API.//// Stable API is a new feature in MongoDB 5.0 that allows user-selectable// API versions, subsets of MongoDB server semantics, to be declared on a// Client. During communication with a server, Clients with a declared API// version will force that server to behave in a manner compatible with the// API version. Declaring an API version on your Client can be used to// ensure consistent responses from a server, providing long term API// stability for an application.//// The declared API version is applied to all commands run through the// Client, including those sent through the generic RunCommand helper.// Specifying stable API options in the command document AND declaring// an API version on the Client is not supported and will lead to undefined// behavior. To run any command with a different API version or without// declaring one, create a separate Client that declares the appropriate API// version.// ServerAPIOptions must be declared with an API version. ServerAPIVersion1// is a constant equal to "1".serverAPI := options.ServerAPI(options.ServerAPIVersion1)serverAPIClient, err := mongo.Connect(context.TODO(),options.Client().SetServerAPIOptions(serverAPI))if err != nil {panic(err)}_ = serverAPIClient// ServerAPIOptions can be declared with a Strict option. Declaring a strict// API version will cause the MongoDB server to reject all commands that are// not part of the declared API version. This includes command options and// aggregation pipeline stages. For example, the following Distinct call// would fail because the distinct command is not part of API version 1:serverAPIStrict := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true)serverAPIStrictClient, err := mongo.Connect(context.TODO(),options.Client().SetServerAPIOptions(serverAPIStrict))if err != nil {panic(err)}coll := serverAPIStrictClient.Database("db").Collection("coll")// Fails with error: (APIStrictError) Provided apiStrict:true, but the// command distinct is not in API Version 1_, err = coll.Distinct(context.TODO(), "distinct", bson.D{})log.Println(err)// ServerAPIOptions can be declared with a DeprecationErrors option.// DeprecationErrors can be used to enable command failures when using// functionality that is deprecated in the declared API version. Note that// at the time of this writing, no deprecations in API version 1 exist.serverAPIDeprecation := options.ServerAPI(options.ServerAPIVersion1).SetDeprecationErrors(true)serverAPIDeprecationClient, err := mongo.Connect(context.TODO(),options.Client().SetServerAPIOptions(serverAPIDeprecation))if err != nil {panic(err)}_ = serverAPIDeprecationClient}Example (X509)¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Configure a Client with X509 authentication// (https://www.mongodb.com/docs/manual/core/security-x.509/).// X509 can be configured with different sets of options in the connection// string:// 1. tlsCAFile (or SslCertificateAuthorityFile): Path to the file with// either a single or bundle of certificate authorities to be considered// trusted when making a TLS connection.// 2. tlsCertificateKeyFile (or SslClientCertificateKeyFile): Path to the// client certificate file or the client private key file. In the case that// both are needed, the files should be concatenated.// The SetAuth client option should also be used. The username field is// optional. If it is not specified, it will be extracted from the// certificate key file. The AuthSource is required to be $external.caFilePath := "path/to/cafile"certificateKeyFilePath := "path/to/client-certificate"// To configure auth via a URI instead of a Credential, append// "&authMechanism=MONGODB-X509" to the URI.uri := "mongodb://host:port/?tlsCAFile=%s&tlsCertificateKeyFile=%s"uri = fmt.Sprintf(uri, caFilePath, certificateKeyFilePath)credential := options.Credential{AuthMechanism: "MONGODB-X509",}clientOpts := options.Client().ApplyURI(uri).SetAuth(credential)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {log.Panic(err)}_ = client} funcNewClientdeprecated
func NewClient(opts ...*options.ClientOptions) (*Client,error)
NewClient creates a new client to connect to a deployment specified by the uri.
When creating an options.ClientOptions, the order the methods are called matters. Later Set*methods will overwrite the values from previous Set* method invocations. This includes theApplyURI method. This allows callers to determine the order of precedence for optionapplication. For instance, if ApplyURI is called before SetAuth, the Credential fromSetAuth will overwrite the values from the connection string. If ApplyURI is calledafter SetAuth, then its values will overwrite those from SetAuth.
The opts parameter is processed using options.MergeClientOptions, which will overwrite entireoption fields of previous options, there is no partial overwriting. For example, if Username isset in the Auth field for the first option, and Password is set for the second but with noUsername, after the merge the Username field will be empty.
Deprecated: UseConnect instead.
func (*Client)Connectdeprecatedadded inv0.0.3
Connect initializes the Client by starting background monitoring goroutines.If the Client was created using the NewClient function, this method must be called before a Client can be used.
Connect starts background goroutines to monitor the state of the deployment and does not do any I/O in the maingoroutine. The Client.Ping method can be used to verify that the connection was created successfully.
Deprecated: Usemongo.Connect instead.
func (*Client)Database¶
func (c *Client) Database(namestring, opts ...*options.DatabaseOptions) *Database
Database returns a handle for a database with the given name configured with the given DatabaseOptions.
func (*Client)Disconnect¶added inv0.0.3
Disconnect closes sockets to the topology referenced by this Client. It willshut down any monitoring goroutines, close the idle connection pool, and willwait until all the in use connections have been returned to the connectionpool and closed before returning. If the context expires via cancellation,deadline, or timeout before the in use connections have returned, the in useconnections will be closed, resulting in the failure of any in flight reador write operations. If this method returns with no errors, all connectionsassociated with this Client have been closed.
func (*Client)ListDatabaseNames¶added inv0.0.3
func (c *Client) ListDatabaseNames(ctxcontext.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string,error)
ListDatabaseNames executes a listDatabases command and returns a slice containing the names of all of the databaseson the server.
The filter parameter must be a document containing query operators and can be used to select which databasesare included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include alldatabases.
The opts parameter can be used to specify options for this operation (see the options.ListDatabasesOptionsdocumentation.)
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listDatabases/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var client *mongo.Client// Use a filter to only select non-empty databases.result, err := client.ListDatabaseNames(context.TODO(),bson.D{{"empty", false}})if err != nil {log.Panic(err)}for _, db := range result {fmt.Println(db)}}func (*Client)ListDatabases¶added inv0.0.3
func (c *Client) ListDatabases(ctxcontext.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult,error)
ListDatabases executes a listDatabases command and returns the result.
The filter parameter must be a document containing query operators and can be used to select whichdatabases are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to includeall databases.
The opts parameter can be used to specify options for this operation (see the options.ListDatabasesOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listDatabases/.
func (*Client)NumberSessionsInProgress¶added inv1.2.0
NumberSessionsInProgress returns the number of sessions that have been started for this client but have not beenclosed (i.e. EndSession has not been called).
func (*Client)Ping¶added inv0.0.14
Ping sends a ping command to verify that the client can connect to the deployment.
The rp parameter is used to determine which server is selected for the operation.If it is nil, the client's read preference is used.
If the server is down, Ping will try to select a server until the client's server selection timeout expires.This can be configured through the ClientOptions.SetServerSelectionTimeout option when creating a new Client.After the timeout expires, a server selection error is returned.
Using Ping reduces application resilience because applications starting up will error if the server is temporarilyunavailable or is failing over (e.g. during autoscaling due to a load spike).
func (*Client)StartSession¶added inv0.0.10
func (c *Client) StartSession(opts ...*options.SessionOptions) (Session,error)
StartSession starts a new session configured with the given options.
StartSession does not actually communicate with the server and will not error if the client isdisconnected.
StartSession is safe to call from multiple goroutines concurrently. However, Sessions returned by StartSession arenot safe for concurrent use by multiple goroutines.
If the DefaultReadConcern, DefaultWriteConcern, or DefaultReadPreference options are not set, the client's readconcern, write concern, or read preference will be used, respectively.
Example (WithTransaction)¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readconcern""go.mongodb.org/mongo-driver/mongo/readpref")func main() {// Assume client is configured with write concern majority and read// preference primary.var client *mongo.Client// Specify the DefaultReadConcern option so any transactions started through// the session will have read concern majority.// The DefaultReadPreference and DefaultWriteConcern options aren't// specified so they will be inheritied from client and be set to primary// and majority, respectively.opts := options.Session().SetDefaultReadConcern(readconcern.Majority())sess, err := client.StartSession(opts)if err != nil {log.Panic(err)}defer sess.EndSession(context.TODO())// Specify the ReadPreference option to set the read preference to primary// preferred for this transaction.txnOpts := options.Transaction().SetReadPreference(readpref.PrimaryPreferred())result, err := sess.WithTransaction(context.TODO(),func(ctx mongo.SessionContext) (interface{}, error) {// Use the mongo.SessionContext as the Context parameter for// InsertOne and FindOne so both operations are run in the same// transaction.coll := client.Database("db").Collection("coll")res, err := coll.InsertOne(ctx, bson.D{{"x", 1}})if err != nil {return nil, err}var result bson.Merr = coll.FindOne(ctx,bson.D{{"_id", res.InsertedID}},).Decode(result)if err != nil {return nil, err}return result, err},txnOpts)if err != nil {log.Panic(err)}fmt.Printf("result: %v\n", result)}func (*Client)UseSession¶added inv0.0.16
UseSession creates a new Session and uses it to create a new SessionContext, which is used to call the fn callback.The SessionContext parameter must be used as the Context parameter for any operations in the fn callback that shouldbe executed under a session. After the callback returns, the created Session is ended, meaning that any in-progresstransactions started by fn will be aborted even if fn returns an error.
UseSession is safe to call from multiple goroutines concurrently. However, the SessionContext passed to theUseSession callback function is not safe for concurrent use by multiple goroutines.
If the ctx parameter already contains a Session, that Session will be replaced with the newly created one.
Any error returned by the fn callback will be returned without any modifications.
func (*Client)UseSessionWithOptions¶added inv0.0.16
func (c *Client) UseSessionWithOptions(ctxcontext.Context, opts *options.SessionOptions, fn func(SessionContext)error)error
UseSessionWithOptions operates like UseSession but uses the given SessionOptions to create the Session.
UseSessionWithOptions is safe to call from multiple goroutines concurrently. However, the SessionContext passed tothe UseSessionWithOptions callback function is not safe for concurrent use by multiple goroutines.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readconcern")func main() {var client *mongo.Client// Specify the DefaultReadConcern option so any transactions started through// the session will have read concern majority.// The DefaultReadPreference and DefaultWriteConcern options aren't// specified so they will be inheritied from client and be set to primary// and majority, respectively.opts := options.Session().SetDefaultReadConcern(readconcern.Majority())err := client.UseSessionWithOptions(context.TODO(),opts,func(ctx mongo.SessionContext) error {// Use the mongo.SessionContext as the Context parameter for// InsertOne and FindOne so both operations are run under the new// Session.if err := ctx.StartTransaction(); err != nil {return err}coll := client.Database("db").Collection("coll")res, err := coll.InsertOne(ctx, bson.D{{"x", 1}})if err != nil {// Abort the transaction after an error. Use// context.Background() to ensure that the abort can complete// successfully even if the context passed to mongo.WithSession// is changed to have a timeout._ = ctx.AbortTransaction(context.Background())return err}var result bson.Merr = coll.FindOne(ctx,bson.D{{"_id", res.InsertedID}},).Decode(result)if err != nil {// Abort the transaction after an error. Use// context.Background() to ensure that the abort can complete// successfully even if the context passed to mongo.WithSession// is changed to have a timeout._ = ctx.AbortTransaction(context.Background())return err}fmt.Println(result)// Use context.Background() to ensure that the commit can complete// successfully even if the context passed to mongo.WithSession is// changed to have a timeout.return ctx.CommitTransaction(context.Background())})if err != nil {log.Panic(err)}}func (*Client)Watch¶added inv0.1.0
func (c *Client) Watch(ctxcontext.Context, pipeline interface{},opts ...*options.ChangeStreamOptions) (*ChangeStream,error)
Watch returns a change stream for all changes on the deployment. Seehttps://www.mongodb.com/docs/manual/changeStreams/ for more information about change streams.
The client must be configured with read concern majority or no read concern for a change stream to be createdsuccessfully.
The pipeline parameter must be an array of documents, each representing a pipeline stage. The pipeline cannot benil or empty. The stage documents must all be non-nil. Seehttps://www.mongodb.com/docs/manual/changeStreams/ for a listof pipeline stages that can be used with change streams. For a pipeline of bson.D documents, the mongo.Pipeline{}type can be used.
The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptionsdocumentation).
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var client *mongo.Client// Specify a pipeline that will only match "insert" events.// Specify the MaxAwaitTimeOption to have each attempt wait two seconds for// new documents.matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)changeStream, err := client.Watch(context.TODO(),mongo.Pipeline{matchStage},opts)if err != nil {log.Panic(err)}// Print out all change stream events in the order they're received.// See the mongo.ChangeStream documentation for more examples of using// change streams.for changeStream.Next(context.TODO()) {fmt.Println(changeStream.Current)}}typeClientEncryption¶added inv1.2.0
type ClientEncryption struct {// contains filtered or unexported fields}ClientEncryption is used to create data keys and explicitly encrypt and decrypt BSON values.
funcNewClientEncryption¶added inv1.2.0
func NewClientEncryption(keyVaultClient *Client, opts ...*options.ClientEncryptionOptions) (*ClientEncryption,error)
NewClientEncryption creates a new ClientEncryption instance configured with the given options.
func (*ClientEncryption)AddKeyAltName¶added inv1.10.0
func (ce *ClientEncryption) AddKeyAltName(ctxcontext.Context, idprimitive.Binary, keyAltNamestring) *SingleResult
AddKeyAltName adds a keyAltName to the keyAltNames array of the key document in the key vault collection with thegiven UUID (BSON binary subtype 0x04). Returns the previous version of the key document.
func (*ClientEncryption)Close¶added inv1.2.0
func (ce *ClientEncryption) Close(ctxcontext.Context)error
Close cleans up any resources associated with the ClientEncryption instance. This includes disconnecting thekey-vault Client instance.
func (*ClientEncryption)CreateDataKey¶added inv1.2.0
func (ce *ClientEncryption) CreateDataKey(ctxcontext.Context, kmsProviderstring,opts ...*options.DataKeyOptions) (primitive.Binary,error)
CreateDataKey creates a new key document and inserts into the key vault collection. Returns the _id of the createddocument as a UUID (BSON binary subtype 0x04).
func (*ClientEncryption)CreateEncryptedCollection¶added inv1.12.0
func (ce *ClientEncryption) CreateEncryptedCollection(ctxcontext.Context,db *Database, collstring, createOpts *options.CreateCollectionOptions,kmsProviderstring, masterKey interface{}) (*Collection,bson.M,error)
CreateEncryptedCollection creates a new collection for Queryable Encryption with the help of automatic generation of new encryption data keys for null keyIds.It returns the created collection and the encrypted fields document used to create it.
func (*ClientEncryption)Decrypt¶added inv1.2.0
Decrypt decrypts an encrypted value (BSON binary of subtype 6) and returns the original BSON value.
func (*ClientEncryption)DeleteKey¶added inv1.10.0
func (ce *ClientEncryption) DeleteKey(ctxcontext.Context, idprimitive.Binary) (*DeleteResult,error)
DeleteKey removes the key document with the given UUID (BSON binary subtype 0x04) from the key vault collection.Returns the result of the internal deleteOne() operation on the key vault collection.
func (*ClientEncryption)Encrypt¶added inv1.2.0
func (ce *ClientEncryption) Encrypt(ctxcontext.Context, valbson.RawValue,opts ...*options.EncryptOptions) (primitive.Binary,error)
Encrypt encrypts a BSON value with the given key and algorithm. Returns an encrypted value (BSON binary of subtype 6).
func (*ClientEncryption)EncryptExpression¶added inv1.12.0
func (ce *ClientEncryption) EncryptExpression(ctxcontext.Context, expr interface{}, result interface{}, opts ...*options.EncryptOptions)error
EncryptExpression encrypts an expression to query a range index.On success, `result` is populated with the resulting BSON document.`expr` is expected to be a BSON document of one of the following forms:1. A Match Expression of this form:{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}2. An Aggregate Expression of this form:{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]$gt may also be $gte. $lt may also be $lte.Only supported for queryType "range"
func (*ClientEncryption)GetKey¶added inv1.10.0
func (ce *ClientEncryption) GetKey(ctxcontext.Context, idprimitive.Binary) *SingleResult
GetKey finds a single key document with the given UUID (BSON binary subtype 0x04). Returns the result of theinternal find() operation on the key vault collection.
func (*ClientEncryption)GetKeyByAltName¶added inv1.10.0
func (ce *ClientEncryption) GetKeyByAltName(ctxcontext.Context, keyAltNamestring) *SingleResult
GetKeyByAltName returns a key document in the key vault collection with the given keyAltName.
func (*ClientEncryption)GetKeys¶added inv1.10.0
func (ce *ClientEncryption) GetKeys(ctxcontext.Context) (*Cursor,error)
GetKeys finds all documents in the key vault collection. Returns the result of the internal find() operation on thekey vault collection.
func (*ClientEncryption)RemoveKeyAltName¶added inv1.10.0
func (ce *ClientEncryption) RemoveKeyAltName(ctxcontext.Context, idprimitive.Binary, keyAltNamestring) *SingleResult
RemoveKeyAltName removes a keyAltName from the keyAltNames array of the key document in the key vault collection withthe given UUID (BSON binary subtype 0x04). Returns the previous version of the key document.
func (*ClientEncryption)RewrapManyDataKey¶added inv1.10.0
func (ce *ClientEncryption) RewrapManyDataKey(ctxcontext.Context, filter interface{},opts ...*options.RewrapManyDataKeyOptions) (*RewrapManyDataKeyResult,error)
RewrapManyDataKey decrypts and encrypts all matching data keys with a possibly new masterKey value. For allmatching documents, this method will overwrite the "masterKey", "updateDate", and "keyMaterial". On error, somematching data keys may have been rewrapped.libmongocrypt 1.5.2 is required. An error is returned if the detected version of libmongocrypt is less than 1.5.2.
typeCollection¶
type Collection struct {// contains filtered or unexported fields}Collection is a handle to a MongoDB collection. It is safe for concurrent use by multiple goroutines.
func (*Collection)Aggregate¶
func (coll *Collection) Aggregate(ctxcontext.Context, pipeline interface{},opts ...*options.AggregateOptions) (*Cursor,error)
Aggregate executes an aggregate command against the collection and returns a cursor over the resulting documents.
The pipeline parameter must be an array of documents, each representing an aggregation stage. The pipeline cannotbe nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, themongo.Pipeline type can be used. Seehttps://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/#db-collection-aggregate-stages for a list ofvalid stages in aggregations.
The opts parameter can be used to specify options for the operation (see the options.AggregateOptions documentation.)
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/aggregate/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Specify a pipeline that will return the number of times each name appears// in the collection.// Specify the MaxTime option to limit the amount of time the operation can// run on the server.groupStage := bson.D{{"$group", bson.D{{"_id", "$name"},{"numTimes", bson.D{{"$sum", 1},}},}},}opts := options.Aggregate().SetMaxTime(2 * time.Second)cursor, err := coll.Aggregate(context.TODO(),mongo.Pipeline{groupStage},opts)if err != nil {log.Panic(err)}// Get a list of all returned documents and print them out.// See the mongo.Cursor documentation for more examples of using cursors.var results []bson.Mif err = cursor.All(context.TODO(), &results); err != nil {log.Panic(err)}for _, result := range results {fmt.Printf("name %v appears %v times\n",result["_id"],result["numTimes"])}}func (*Collection)BulkWrite¶added inv0.0.16
func (coll *Collection) BulkWrite(ctxcontext.Context, models []WriteModel,opts ...*options.BulkWriteOptions) (*BulkWriteResult,error)
BulkWrite performs a bulk write operation (https://www.mongodb.com/docs/manual/core/bulk-write-operations/).
The models parameter must be a slice of operations to be executed in this bulk write. It cannot be nil or empty.All of the models must be non-nil. See the mongo.WriteModel documentation for a list of valid model types andexamples of how they should be used.
The opts parameter can be used to specify options for the operation (see the options.BulkWriteOptions documentation.)
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar firstID, secondID primitive.ObjectID// Update the "email" field for two users.// For each update, specify the Upsert option to insert a new document if a// document matching the filter isn't found.// Set the Ordered option to false to allow both operations to happen even// if one of them errors.firstUpdate := bson.D{{"$set", bson.D{{"email", "firstEmail@example.com"},}},}secondUpdate := bson.D{{"$set", bson.D{{"email", "secondEmail@example.com"},}},}models := []mongo.WriteModel{mongo.NewUpdateOneModel().SetFilter(bson.D{{"_id", firstID}}).SetUpdate(firstUpdate).SetUpsert(true),mongo.NewUpdateOneModel().SetFilter(bson.D{{"_id", secondID}}).SetUpdate(secondUpdate).SetUpsert(true),}opts := options.BulkWrite().SetOrdered(false)res, err := coll.BulkWrite(context.TODO(), models, opts)if err != nil {log.Panic(err)}fmt.Printf("inserted %v and deleted %v documents\n",res.InsertedCount,res.DeletedCount)}func (*Collection)Clone¶added inv0.0.9
func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection,error)
Clone creates a copy of the Collection configured with the given CollectionOptions.The specified options are merged with the existing options on the collection, with the specified options takingprecedence.
func (*Collection)CountDocuments¶added inv0.0.11
func (coll *Collection) CountDocuments(ctxcontext.Context, filter interface{},opts ...*options.CountOptions) (int64,error)
CountDocuments returns the number of documents in the collection. For a fast count of the documents in thecollection, see the EstimatedDocumentCount method.
The filter parameter must be a document and can be used to select which documents contribute to the count. Itcannot be nil. An empty document (e.g. bson.D{}) should be used to count all documents in the collection. This willresult in a full collection scan.
The opts parameter can be used to specify options for the operation (see the options.CountOptions documentation).
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Count the number of times the name "Bob" appears in the collection.// Specify the MaxTime option to limit the amount of time the operation can// run on the server.opts := options.Count().SetMaxTime(2 * time.Second)count, err := coll.CountDocuments(context.TODO(),bson.D{{"name", "Bob"}},opts)if err != nil {log.Panic(err)}fmt.Printf("name Bob appears in %v documents", count)}func (*Collection)Database¶added inv0.0.15
func (coll *Collection) Database() *Database
Database returns the Database that was used to create the Collection.
func (*Collection)DeleteMany¶
func (coll *Collection) DeleteMany(ctxcontext.Context, filter interface{},opts ...*options.DeleteOptions) (*DeleteResult,error)
DeleteMany executes a delete command to delete documents from the collection.
The filter parameter must be a document containing query operators and can be used to select the documents tobe deleted. It cannot be nil. An empty document (e.g. bson.D{}) should be used to delete all documents in thecollection. If the filter does not match any documents, the operation will succeed and a DeleteResult with aDeletedCount of 0 will be returned.
The opts parameter can be used to specify options for the operation (see the options.DeleteOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/delete/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Delete all documents in which the "name" field is "Bob" or "bob".// Specify the Collation option to provide a collation that will ignore case// for string comparisons.opts := options.Delete().SetCollation(&options.Collation{Locale: "en_US",Strength: 1,CaseLevel: false,})res, err := coll.DeleteMany(context.TODO(), bson.D{{"name", "bob"}}, opts)if err != nil {log.Panic(err)}fmt.Printf("deleted %v documents\n", res.DeletedCount)}func (*Collection)DeleteOne¶
func (coll *Collection) DeleteOne(ctxcontext.Context, filter interface{},opts ...*options.DeleteOptions) (*DeleteResult,error)
DeleteOne executes a delete command to delete at most one document from the collection.
The filter parameter must be a document containing query operators and can be used to select the document to bedeleted. It cannot be nil. If the filter does not match any documents, the operation will succeed and a DeleteResultwith a DeletedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from thematched set.
The opts parameter can be used to specify options for the operation (see the options.DeleteOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/delete/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Delete at most one document in which the "name" field is "Bob" or "bob".// Specify the SetCollation option to provide a collation that will ignore// case for string comparisons.opts := options.Delete().SetCollation(&options.Collation{Locale: "en_US",Strength: 1,CaseLevel: false,})res, err := coll.DeleteOne(context.TODO(), bson.D{{"name", "bob"}}, opts)if err != nil {log.Panic(err)}fmt.Printf("deleted %v documents\n", res.DeletedCount)}func (*Collection)Distinct¶
func (coll *Collection) Distinct(ctxcontext.Context, fieldNamestring, filter interface{},opts ...*options.DistinctOptions) ([]interface{},error)
Distinct executes a distinct command to find the unique values for a specified field in the collection.
The fieldName parameter specifies the field name for which distinct values should be returned.
The filter parameter must be a document containing query operators and can be used to select which documents areconsidered. It cannot be nil. An empty document (e.g. bson.D{}) should be used to select all documents.
The opts parameter can be used to specify options for the operation (see the options.DistinctOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/distinct/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Find all unique values for the "name" field for documents in which the// "age" field is greater than 25.// Specify the MaxTime option to limit the amount of time the operation can// run on the server.filter := bson.D{{"age", bson.D{{"$gt", 25}}}}opts := options.Distinct().SetMaxTime(2 * time.Second)values, err := coll.Distinct(context.TODO(), "name", filter, opts)if err != nil {log.Panic(err)}for _, value := range values {fmt.Println(value)}}func (*Collection)Drop¶added inv0.0.4
func (coll *Collection) Drop(ctxcontext.Context)error
Drop drops the collection on the server. This method ignores "namespace not found" errors so it is safe to dropa collection that does not exist on the server.
func (*Collection)EstimatedDocumentCount¶added inv0.0.11
func (coll *Collection) EstimatedDocumentCount(ctxcontext.Context,opts ...*options.EstimatedDocumentCountOptions) (int64,error)
EstimatedDocumentCount executes a count command and returns an estimate of the number of documents in the collectionusing collection metadata.
The opts parameter can be used to specify options for the operation (see the options.EstimatedDocumentCountOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/count/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Get and print an estimated of the number of documents in the collection.// Specify the MaxTime option to limit the amount of time the operation can// run on the server.opts := options.EstimatedDocumentCount().SetMaxTime(2 * time.Second)count, err := coll.EstimatedDocumentCount(context.TODO(), opts)if err != nil {log.Panic(err)}fmt.Printf("estimated document count: %v", count)}func (*Collection)Find¶
func (coll *Collection) Find(ctxcontext.Context, filter interface{},opts ...*options.FindOptions) (cur *Cursor, errerror)
Find executes a find command and returns a Cursor over the matching documents in the collection.
The filter parameter must be a document containing query operators and can be used to select which documents areincluded in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all documents.
The opts parameter can be used to specify options for the operation (see the options.FindOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/find/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Find all documents in which the "name" field is "Bob".// Specify the Sort option to sort the returned documents by age in// ascending order.opts := options.Find().SetSort(bson.D{{"age", 1}})cursor, err := coll.Find(context.TODO(), bson.D{{"name", "Bob"}}, opts)if err != nil {log.Panic(err)}// Get a list of all returned documents and print them out.// See the mongo.Cursor documentation for more examples of using cursors.var results []bson.Mif err = cursor.All(context.TODO(), &results); err != nil {log.Panic(err)}for _, result := range results {fmt.Println(result)}}Example (PrimitiveRegex)¶
package mainimport ("context""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {ctx := context.TODO()clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")// Connect to a mongodb server.client, err := mongo.Connect(ctx, clientOptions)if err != nil {panic(err)}defer func() { _ = client.Disconnect(ctx) }()type Pet struct {Type string `bson:"type"`Name string `bson:"name"`}// Create a slice of documents to insert. We will lookup a subset of// these documents using regex.toInsert := []interface{}{Pet{Type: "cat", Name: "Mo"},Pet{Type: "dog", Name: "Loki"},}coll := client.Database("test").Collection("test")if _, err := coll.InsertMany(ctx, toInsert); err != nil {panic(err)}// Create a filter to find a document with key "name" and any value that// starts with letter "m". Use the "i" option to indicate// case-insensitivity.filter := bson.D{{"name", primitive.Regex{Pattern: "^m", Options: "i"}}}_, err = coll.Find(ctx, filter)if err != nil {panic(err)}}Example (Regex)¶
package mainimport ("context""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {ctx := context.TODO()clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")// Connect to a mongodb server.client, err := mongo.Connect(ctx, clientOptions)if err != nil {panic(err)}defer func() { _ = client.Disconnect(ctx) }()type Pet struct {Type string `bson:"type"`Name string `bson:"name"`}// Create a slice of documents to insert. We will lookup a subset of// these documents using regex.toInsert := []interface{}{Pet{Type: "cat", Name: "Mo"},Pet{Type: "dog", Name: "Loki"},}coll := client.Database("test").Collection("test")if _, err := coll.InsertMany(ctx, toInsert); err != nil {panic(err)}// Create a filter to find a document with key "name" and any value that// starts with letter "m". Use the "i" option to indicate// case-insensitivity.filter := bson.D{{"name", bson.D{{"$regex", "^m"}, {"$options", "i"}}}}_, err = coll.Find(ctx, filter)if err != nil {panic(err)}}func (*Collection)FindOne¶
func (coll *Collection) FindOne(ctxcontext.Context, filter interface{},opts ...*options.FindOneOptions) *SingleResult
FindOne executes a find command and returns a SingleResult for one document in the collection.
The filter parameter must be a document containing query operators and can be used to select the document to bereturned. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set toErrNoDocuments will be returned. If the filter matches multiple documents, one will be selected from the matched set.
The opts parameter can be used to specify options for this operation (see the options.FindOneOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/find/.
Example¶
package mainimport ("context""errors""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find the document for which the _id field matches id.// Specify the Sort option to sort the documents by age.// The first document in the sorted order will be returned.opts := options.FindOne().SetSort(bson.D{{"age", 1}})var result bson.Merr := coll.FindOne(context.TODO(),bson.D{{"_id", id}},opts,).Decode(&result)if err != nil {// ErrNoDocuments means that the filter did not match any documents in// the collection.if errors.Is(err, mongo.ErrNoDocuments) {return}log.Panic(err)}fmt.Printf("found document %v", result)}func (*Collection)FindOneAndDelete¶
func (coll *Collection) FindOneAndDelete(ctxcontext.Context, filter interface{},opts ...*options.FindOneAndDeleteOptions) *SingleResult
FindOneAndDelete executes a findAndModify command to delete at most one document in the collection. and returns thedocument as it appeared before deletion.
The filter parameter must be a document containing query operators and can be used to select the document to bedeleted. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set toErrNoDocuments wil be returned. If the filter matches multiple documents, one will be selected from the matched set.
The opts parameter can be used to specify options for the operation (see the options.FindOneAndDeleteOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/findAndModify/.
Example¶
package mainimport ("context""errors""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find and delete the document for which the _id field matches id.// Specify the Projection option to only include the name and age fields in// the returned document.opts := options.FindOneAndDelete().SetProjection(bson.D{{"name", 1}, {"age", 1}})var deletedDocument bson.Merr := coll.FindOneAndDelete(context.TODO(),bson.D{{"_id", id}},opts,).Decode(&deletedDocument)if err != nil {// ErrNoDocuments means that the filter did not match any documents in// the collection.if errors.Is(err, mongo.ErrNoDocuments) {return}log.Panic(err)}fmt.Printf("deleted document %v", deletedDocument)}func (*Collection)FindOneAndReplace¶
func (coll *Collection) FindOneAndReplace(ctxcontext.Context, filter interface{},replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *SingleResult
FindOneAndReplace executes a findAndModify command to replace at most one document in the collectionand returns the document as it appeared before replacement.
The filter parameter must be a document containing query operators and can be used to select the document to bereplaced. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set toErrNoDocuments wil be returned. If the filter matches multiple documents, one will be selected from the matched set.
The replacement parameter must be a document that will be used to replace the selected document. It cannot be niland cannot contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/).
The opts parameter can be used to specify options for the operation (see the options.FindOneAndReplaceOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/findAndModify/.
Example¶
package mainimport ("context""errors""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find the document for which the _id field matches id and add a field// called "location".// Specify the Upsert option to insert a new document if a document matching// the filter isn't found.opts := options.FindOneAndReplace().SetUpsert(true)filter := bson.D{{"_id", id}}replacement := bson.D{{"location", "NYC"}}var replacedDocument bson.Merr := coll.FindOneAndReplace(context.TODO(),filter,replacement,opts,).Decode(&replacedDocument)if err != nil {// ErrNoDocuments means that the filter did not match any documents in// the collection.if errors.Is(err, mongo.ErrNoDocuments) {return}log.Panic(err)}fmt.Printf("replaced document %v", replacedDocument)}func (*Collection)FindOneAndUpdate¶
func (coll *Collection) FindOneAndUpdate(ctxcontext.Context, filter interface{},update interface{}, opts ...*options.FindOneAndUpdateOptions) *SingleResult
FindOneAndUpdate executes a findAndModify command to update at most one document in the collection and returns thedocument as it appeared before updating.
The filter parameter must be a document containing query operators and can be used to select the document to beupdated. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set toErrNoDocuments wil be returned. If the filter matches multiple documents, one will be selected from the matched set.
The update parameter must be a document containing update operators(https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to be madeto the selected document. It cannot be nil or empty.
The opts parameter can be used to specify options for the operation (see the options.FindOneAndUpdateOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/findAndModify/.
Example¶
package mainimport ("context""errors""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find the document for which the _id field matches id and set the email to// "newemail@example.com".// Specify the Upsert option to insert a new document if a document matching// the filter isn't found.opts := options.FindOneAndUpdate().SetUpsert(true)filter := bson.D{{"_id", id}}update := bson.D{{"$set", bson.D{{"email", "newemail@example.com"}}}}var updatedDocument bson.Merr := coll.FindOneAndUpdate(context.TODO(),filter,update,opts,).Decode(&updatedDocument)if err != nil {// ErrNoDocuments means that the filter did not match any documents in// the collection.if errors.Is(err, mongo.ErrNoDocuments) {return}log.Panic(err)}fmt.Printf("updated document %v", updatedDocument)}func (*Collection)Indexes¶added inv0.0.3
func (coll *Collection) Indexes()IndexView
Indexes returns an IndexView instance that can be used to perform operations on the indexes for the collection.
func (*Collection)InsertMany¶
func (coll *Collection) InsertMany(ctxcontext.Context, documents []interface{},opts ...*options.InsertManyOptions) (*InsertManyResult,error)
InsertMany executes an insert command to insert multiple documents into the collection. If write errors occurduring the operation (e.g. duplicate key error), this method returns a BulkWriteException error.
The documents parameter must be a slice of documents to insert. The slice cannot be nil or empty. The elements mustall be non-nil. For any document that does not have an _id field when transformed into BSON, one will be addedautomatically to the marshalled document. The original document will not be modified. The _id values for the inserteddocuments can be retrieved from the InsertedIDs field of the returned InsertManyResult.
The opts parameter can be used to specify options for the operation (see the options.InsertManyOptions documentation.)
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/insert/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collection// Insert documents {name: "Alice"} and {name: "Bob"}.// Set the Ordered option to false to allow both operations to happen even// if one of them errors.docs := []interface{}{bson.D{{"name", "Alice"}},bson.D{{"name", "Bob"}},}opts := options.InsertMany().SetOrdered(false)res, err := coll.InsertMany(context.TODO(), docs, opts)if err != nil {log.Panic(err)}fmt.Printf("inserted documents with IDs %v\n", res.InsertedIDs)}func (*Collection)InsertOne¶
func (coll *Collection) InsertOne(ctxcontext.Context, document interface{},opts ...*options.InsertOneOptions) (*InsertOneResult,error)
InsertOne executes an insert command to insert a single document into the collection.
The document parameter must be the document to be inserted. It cannot be nil. If the document does not have an _idfield when transformed into BSON, one will be added automatically to the marshalled document. The original documentwill not be modified. The _id can be retrieved from the InsertedID field of the returned InsertOneResult.
The opts parameter can be used to specify options for the operation (see the options.InsertOneOptions documentation.)
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/insert/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var coll *mongo.Collection// Insert the document {name: "Alice"}.res, err := coll.InsertOne(context.TODO(), bson.D{{"name", "Alice"}})if err != nil {log.Panic(err)}fmt.Printf("inserted document with ID %v\n", res.InsertedID)}func (*Collection)Name¶added inv0.0.4
func (coll *Collection) Name()string
Name returns the name of the collection.
func (*Collection)ReplaceOne¶
func (coll *Collection) ReplaceOne(ctxcontext.Context, filter interface{},replacement interface{}, opts ...*options.ReplaceOptions) (*UpdateResult,error)
ReplaceOne executes an update command to replace at most one document in the collection.
The filter parameter must be a document containing query operators and can be used to select the document to bereplaced. It cannot be nil. If the filter does not match any documents, the operation will succeed and anUpdateResult with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will beselected from the matched set and MatchedCount will equal 1.
The replacement parameter must be a document that will be used to replace the selected document. It cannot be niland cannot contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/).
The opts parameter can be used to specify options for the operation (see the options.ReplaceOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/update/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find the document for which the _id field matches id and add a field// called "location".// Specify the Upsert option to insert a new document if a document matching// the filter isn't found.opts := options.Replace().SetUpsert(true)filter := bson.D{{"_id", id}}replacement := bson.D{{"location", "NYC"}}result, err := coll.ReplaceOne(context.TODO(), filter, replacement, opts)if err != nil {log.Panic(err)}if result.MatchedCount != 0 {fmt.Println("matched and replaced an existing document")return}if result.UpsertedCount != 0 {fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)}}func (*Collection)SearchIndexes¶added inv1.13.0
func (coll *Collection) SearchIndexes()SearchIndexView
SearchIndexes returns a SearchIndexView instance that can be used to perform operations on the search indexes for the collection.
func (*Collection)UpdateByID¶added inv1.5.0
func (coll *Collection) UpdateByID(ctxcontext.Context, id interface{}, update interface{},opts ...*options.UpdateOptions) (*UpdateResult,error)
UpdateByID executes an update command to update the document whose _id value matches the provided ID in the collection.This is equivalent to running UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...).
The id parameter is the _id of the document to be updated. It cannot be nil. If the ID does not match any documents,the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned.
The update parameter must be a document containing update operators(https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to bemade to the selected document. It cannot be nil or empty.
The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/update/.
func (*Collection)UpdateMany¶
func (coll *Collection) UpdateMany(ctxcontext.Context, filter interface{}, update interface{},opts ...*options.UpdateOptions) (*UpdateResult,error)
UpdateMany executes an update command to update documents in the collection.
The filter parameter must be a document containing query operators and can be used to select the documents to beupdated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResultwith a MatchedCount of 0 will be returned.
The update parameter must be a document containing update operators(https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to be madeto the selected documents. It cannot be nil or empty.
The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/update/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var coll *mongo.Collection// Increment the age for all users whose birthday is today.today := time.Now().Format("01-01-1970")filter := bson.D{{"birthday", today}}update := bson.D{{"$inc", bson.D{{"age", 1}}}}result, err := coll.UpdateMany(context.TODO(), filter, update)if err != nil {log.Panic(err)}if result.MatchedCount != 0 {fmt.Println("matched and replaced an existing document")return}}func (*Collection)UpdateOne¶
func (coll *Collection) UpdateOne(ctxcontext.Context, filter interface{}, update interface{},opts ...*options.UpdateOptions) (*UpdateResult,error)
UpdateOne executes an update command to update at most one document in the collection.
The filter parameter must be a document containing query operators and can be used to select the document to beupdated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResultwith a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from thematched set and MatchedCount will equal 1.
The update parameter must be a document containing update operators(https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to bemade to the selected document. It cannot be nil or empty.
The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/update/.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/bson/primitive""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var coll *mongo.Collectionvar id primitive.ObjectID// Find the document for which the _id field matches id and set the email to// "newemail@example.com".// Specify the Upsert option to insert a new document if a document matching// the filter isn't found.opts := options.Update().SetUpsert(true)filter := bson.D{{"_id", id}}update := bson.D{{"$set", bson.D{{"email", "newemail@example.com"}}}}result, err := coll.UpdateOne(context.TODO(), filter, update, opts)if err != nil {log.Panic(err)}if result.MatchedCount != 0 {fmt.Println("matched and replaced an existing document")return}if result.UpsertedCount != 0 {fmt.Printf("inserted a new document with ID %v\n", result.UpsertedID)}}func (*Collection)Watch¶added inv0.0.2
func (coll *Collection) Watch(ctxcontext.Context, pipeline interface{},opts ...*options.ChangeStreamOptions) (*ChangeStream,error)
Watch returns a change stream for all changes on the corresponding collection. Seehttps://www.mongodb.com/docs/manual/changeStreams/ for more information about change streams.
The Collection must be configured with read concern majority or no read concern for a change stream to be createdsuccessfully.
The pipeline parameter must be an array of documents, each representing a pipeline stage. The pipeline cannot benil but can be empty. The stage documents must all be non-nil. Seehttps://www.mongodb.com/docs/manual/changeStreams/ fora list of pipeline stages that can be used with change streams. For a pipeline of bson.D documents, themongo.Pipeline{} type can be used.
The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptionsdocumentation).
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var collection *mongo.Collection// Specify a pipeline that will only match "insert" events.// Specify the MaxAwaitTimeOption to have each attempt wait two seconds for// new documents.matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)changeStream, err := collection.Watch(context.TODO(),mongo.Pipeline{matchStage},opts)if err != nil {log.Panic(err)}// Print out all change stream events in the order they're received.// See the mongo.ChangeStream documentation for more examples of using// change streams.for changeStream.Next(context.TODO()) {fmt.Println(changeStream.Current)}}typeCollectionSpecification¶added inv1.5.0
type CollectionSpecification struct {// The collection name.Namestring// The type of the collection. This will either be "collection" or "view".Typestring// Whether or not the collection is readOnly. This will be false for MongoDB versions < 3.4.ReadOnlybool// The collection UUID. This field will be nil for MongoDB versions < 3.6. For versions 3.6 and higher, this will// be a primitive.Binary with Subtype 4.UUID *primitive.Binary// A document containing the options used to construct the collection.Optionsbson.Raw// An IndexSpecification instance with details about the collection's _id index. This will be nil if the NameOnly// option is used and for MongoDB versions < 3.4.IDIndex *IndexSpecification}CollectionSpecification represents a collection in a database. This type is returned by theDatabase.ListCollectionSpecifications function.
func (*CollectionSpecification)UnmarshalBSONdeprecatedadded inv1.5.0
func (cs *CollectionSpecification) UnmarshalBSON(data []byte)error
UnmarshalBSON implements the bson.Unmarshaler interface.
Deprecated: Unmarshaling a CollectionSpecification from BSON will not be supported in Go Driver2.0.
typeCommandError¶added inv1.0.0
type CommandError struct {Codeint32MessagestringLabels []string// Categories to which the error belongsNamestring// A human-readable name corresponding to the error codeWrappederror// The underlying error, if one exists.Rawbson.Raw// The original server response containing the error.}CommandError represents a server error during execution of a command. This can be returned by any operation.
func (CommandError)Error¶added inv1.0.0
func (eCommandError) Error()string
Error implements the error interface.
func (CommandError)HasErrorCode¶added inv1.5.0
func (eCommandError) HasErrorCode(codeint)bool
HasErrorCode returns true if the error has the specified code.
func (CommandError)HasErrorCodeWithMessage¶added inv1.5.0
func (eCommandError) HasErrorCodeWithMessage(codeint, messagestring)bool
HasErrorCodeWithMessage returns true if the error has the specified code and Message contains the specified message.
func (CommandError)HasErrorLabel¶added inv1.0.0
func (eCommandError) HasErrorLabel(labelstring)bool
HasErrorLabel returns true if the error contains the specified label.
func (CommandError)HasErrorMessage¶added inv1.5.0
func (eCommandError) HasErrorMessage(messagestring)bool
HasErrorMessage returns true if the error contains the specified message.
func (CommandError)IsMaxTimeMSExpiredError¶added inv1.1.0
func (eCommandError) IsMaxTimeMSExpiredError()bool
IsMaxTimeMSExpiredError returns true if the error is a MaxTimeMSExpired error.
func (CommandError)Unwrap¶added inv1.4.0
func (eCommandError) Unwrap()error
Unwrap returns the underlying error.
typeCursor¶
type Cursor struct {// Current contains the BSON bytes of the current change document. This property is only valid until the next call// to Next or TryNext. If continued access is required, a copy must be made.Currentbson.Raw// contains filtered or unexported fields}Cursor is used to iterate over a stream of documents. Each document can be decoded into a Go type via the Decodemethod or accessed as raw BSON via the Current field. This type is not goroutine safe and must not be usedconcurrently by multiple goroutines.
funcNewCursorFromDocuments¶added inv1.9.0
func NewCursorFromDocuments(documents []interface{}, errerror, registry *bsoncodec.Registry) (*Cursor,error)NewCursorFromDocuments creates a new Cursor pre-loaded with the provided documents, error and registry. If no registry is provided,bson.DefaultRegistry will be used.
The documents parameter must be a slice of documents. The slice may be nil or empty, but all elements must be non-nil.
func (*Cursor)All¶added inv1.1.0
All iterates the cursor and decodes each document into results. The results parameter must be a pointer to a slice.The slice pointed to by results will be completely overwritten. A nil slice pointer will not be modified if the cursorhas been closed, exhausted, or is empty. This method will close the cursor after retrieving all documents. If thecursor has been iterated, any previously iterated documents will not be included in results.
This method requires driver version >= 1.1.0.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var cursor *mongo.Cursorvar results []bson.Mif err := cursor.All(context.TODO(), &results); err != nil {log.Panic(err)}fmt.Println(results)}func (*Cursor)Close¶added inv0.0.2
Close closes this cursor. Next and TryNext must not be called after Close has been called. Close is idempotent. Afterthe first call, any subsequent calls will not change the state.
func (*Cursor)Decode¶added inv0.0.2
Decode will unmarshal the current document into val and return any errors from the unmarshalling process without anymodification. If val is nil or is a typed nil, an error will be returned.
func (*Cursor)Err¶added inv0.0.2
Err returns the last error seen by the Cursor, or nil if no error has occurred.
func (*Cursor)ID¶added inv0.0.2
ID returns the ID of this cursor, or 0 if the cursor has been closed or exhausted.
func (*Cursor)Next¶added inv0.0.2
Next gets the next document for this cursor. It returns true if there were no errors and the cursor has not beenexhausted.
Next blocks until a document is available or an error occurs. If the context expires, the cursor's error willbe set to ctx.Err(). In case of an error, Next will return false.
If Next returns false, subsequent calls will also return false.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var cursor *mongo.Cursordefer cursor.Close(context.TODO())// Iterate the cursor and print out each document until the cursor is// exhausted or there is an error getting the next document.for cursor.Next(context.TODO()) {// A new result variable should be declared for each document.var result bson.Mif err := cursor.Decode(&result); err != nil {log.Panic(err)}fmt.Println(result)}if err := cursor.Err(); err != nil {log.Panic(err)}}func (*Cursor)RemainingBatchLength¶added inv1.4.0
RemainingBatchLength returns the number of documents left in the current batch. If this returns zero, the subsequentcall to Next or TryNext will do a network request to fetch the next batch.
Example¶
package mainimport ("context""fmt""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Because we're using a tailable cursor, this must be a handle to a capped// collection.var coll *mongo.Collection// Create a tailable await cursor. Specify the MaxAwaitTime option so// requests to get more data will return if there are no documents available// after two seconds.findOpts := options.Find().SetCursorType(options.TailableAwait).SetMaxAwaitTime(2 * time.Second)cursor, err := coll.Find(context.TODO(), bson.D{}, findOpts)if err != nil {panic(err)}for {// Iterate the cursor using TryNext.if cursor.TryNext(context.TODO()) {fmt.Println(cursor.Current)}// Handle cursor errors or the cursor being closed by the server.if err = cursor.Err(); err != nil {panic(err)}if cursor.ID() == 0 {panic("cursor was unexpectedly closed by the server")}// Use the RemainingBatchLength function to rate-limit the number of// network requests the driver does. If the current batch is empty,// sleep for a short amount of time to let documents build up on the// server before the next TryNext call, which will do a network request.if cursor.RemainingBatchLength() == 0 {time.Sleep(100 * time.Millisecond)}}}func (*Cursor)SetBatchSize¶added inv1.11.7
SetBatchSize sets the number of documents to fetch from the database witheach iteration of the cursor's "Next" method. Note that some operations setan initial cursor batch size, so this setting only affects subsequentdocument batches fetched from the database.
func (*Cursor)SetComment¶added inv1.13.0
func (c *Cursor) SetComment(comment interface{})
SetComment will set a user-configurable comment that can be used to identifythe operation in server logs.
func (*Cursor)SetMaxTime¶added inv1.13.0
SetMaxTime will set the maximum amount of time the server will allow theoperations to execute. The server will error if this field is set but thecursor is not configured with awaitData=true.
The time.Duration value passed by this setter will be converted and roundeddown to the nearest millisecond.
func (*Cursor)TryNext¶added inv1.2.0
TryNext attempts to get the next document for this cursor. It returns true if there were no errors and the nextdocument is available. This is only recommended for use with tailable cursors as a non-blocking alternative toNext. Seehttps://www.mongodb.com/docs/manual/core/tailable-cursors/ for more information about tailable cursors.
TryNext returns false if the cursor is exhausted, an error occurs when getting results from the server, the nextdocument is not yet available, or ctx expires. If the context expires, the cursor's error will be set to ctx.Err().
If TryNext returns false and an error occurred or the cursor has been exhausted (i.e. c.Err() != nil || c.ID() == 0),subsequent attempts will also return false. Otherwise, it is safe to call TryNext again until a document isavailable.
This method requires driver version >= 1.2.0.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var cursor *mongo.Cursordefer cursor.Close(context.TODO())// Iterate the cursor and print out each document until the cursor is// exhausted or there is an error getting the next document.for {if cursor.TryNext(context.TODO()) {// A new result variable should be declared for each document.var result bson.Mif err := cursor.Decode(&result); err != nil {log.Panic(err)}fmt.Println(result)continue}// If TryNext returns false, the next document is not yet available, the// cursor was exhausted and was closed, or an error occurred. TryNext// should only be called again for the empty batch case.if err := cursor.Err(); err != nil {log.Panic(err)}if cursor.ID() == 0 {break}}}typeDatabase¶
type Database struct {// contains filtered or unexported fields}Database is a handle to a MongoDB database. It is safe for concurrent use by multiple goroutines.
func (*Database)Aggregate¶added inv1.1.0
func (db *Database) Aggregate(ctxcontext.Context, pipeline interface{},opts ...*options.AggregateOptions) (*Cursor,error)
Aggregate executes an aggregate command the database. This requires MongoDB version >= 3.6 and driver version >=1.1.0.
The pipeline parameter must be a slice of documents, each representing an aggregation stage. The pipelinecannot be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, themongo.Pipeline type can be used. Seehttps://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/#db-aggregate-stages for a list of validstages in database-level aggregations.
The opts parameter can be used to specify options for this operation (see the options.AggregateOptions documentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/aggregate/.
func (*Database)Collection¶
func (db *Database) Collection(namestring, opts ...*options.CollectionOptions) *Collection
Collection gets a handle for a collection with the given name configured with the given CollectionOptions.
func (*Database)CreateCollection¶added inv1.4.0
func (db *Database) CreateCollection(ctxcontext.Context, namestring, opts ...*options.CreateCollectionOptions)error
CreateCollection executes a create command to explicitly create a new collection with the specified name on theserver. If the collection being created already exists, this method will return a mongo.CommandError. This methodrequires driver version 1.4.0 or higher.
The opts parameter can be used to specify options for the operation (see the options.CreateCollectionOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/create/.
Example¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var db *mongo.Database// Create a "users" collection with a JSON schema validator. The validator// will ensure that each document in the collection has "name" and "age"// fields.jsonSchema := bson.M{"bsonType": "object","required": []string{"name", "age"},"properties": bson.M{"name": bson.M{"bsonType": "string","description": "the name of the user, which is required and " +"must be a string",},"age": bson.M{"bsonType": "int","minimum": 18,"description": "the age of the user, which is required and " +"must be an integer >= 18",},},}validator := bson.M{"$jsonSchema": jsonSchema,}opts := options.CreateCollection().SetValidator(validator)err := db.CreateCollection(context.TODO(), "users", opts)if err != nil {log.Panic(err)}}func (*Database)CreateView¶added inv1.4.0
func (db *Database) CreateView(ctxcontext.Context, viewName, viewOnstring, pipeline interface{},opts ...*options.CreateViewOptions)error
CreateView executes a create command to explicitly create a view on the server. Seehttps://www.mongodb.com/docs/manual/core/views/ for more information about views. This method requires driver version >=1.4.0 and MongoDB version >= 3.4.
The viewName parameter specifies the name of the view to create.
The viewOn parameter specifies the name of the collection or view on which this view will be created¶
The pipeline parameter specifies an aggregation pipeline that will be exececuted against the source collection orview to create this view.
The opts parameter can be used to specify options for the operation (see the options.CreateViewOptionsdocumentation).
Example¶
package mainimport ("context""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var db *mongo.Database// Create a view on the "users" collection called "usernames". Specify a// pipeline that concatenates the "firstName" and "lastName" fields from// each document in "users" and projects the result into the "fullName"// field in the view.projectStage := bson.D{{"$project", bson.D{{"_id", 0},{"fullName", bson.D{{"$concat", []string{"$firstName", " ", "$lastName"}},}},}},}pipeline := mongo.Pipeline{projectStage}// Specify the Collation option to set a default collation for the view.opts := options.CreateView().SetCollation(&options.Collation{Locale: "en_US",})err := db.CreateView(context.TODO(), "usernames", "users", pipeline, opts)if err != nil {log.Panic(err)}}func (*Database)Drop¶added inv0.0.4
Drop drops the database on the server. This method ignores "namespace not found" errors so it is safe to dropa database that does not exist on the server.
func (*Database)ListCollectionNames¶added inv1.1.0
func (db *Database) ListCollectionNames(ctxcontext.Context, filter interface{}, opts ...*options.ListCollectionsOptions) ([]string,error)
ListCollectionNames executes a listCollections command and returns a slice containing the names of the collectionsin the database. This method requires driver version >= 1.1.0.
The filter parameter must be a document containing query operators and can be used to select which collectionsare included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include allcollections.
The opts parameter can be used to specify options for the operation (see the options.ListCollectionsOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listCollections/.
BUG(benjirewis): ListCollectionNames prevents listing more than 100 collections per database when running againstMongoDB version 2.6.
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var db *mongo.Database// Use a filter to only select capped collections.result, err := db.ListCollectionNames(context.TODO(),bson.D{{"options.capped", true}})if err != nil {log.Panic(err)}for _, coll := range result {fmt.Println(coll)}}func (*Database)ListCollectionSpecifications¶added inv1.5.0
func (db *Database) ListCollectionSpecifications(ctxcontext.Context, filter interface{},opts ...*options.ListCollectionsOptions) ([]*CollectionSpecification,error)
ListCollectionSpecifications executes a listCollections command and returns a slice of CollectionSpecificationinstances representing the collections in the database.
The filter parameter must be a document containing query operators and can be used to select which collectionsare included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include allcollections.
The opts parameter can be used to specify options for the operation (see the options.ListCollectionsOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listCollections/.
BUG(benjirewis): ListCollectionSpecifications prevents listing more than 100 collections per database when runningagainst MongoDB version 2.6.
func (*Database)ListCollections¶added inv0.0.6
func (db *Database) ListCollections(ctxcontext.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (*Cursor,error)
ListCollections executes a listCollections command and returns a cursor over the collections in the database.
The filter parameter must be a document containing query operators and can be used to select which collectionsare included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include allcollections.
The opts parameter can be used to specify options for the operation (see the options.ListCollectionsOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listCollections/.
BUG(benjirewis): ListCollections prevents listing more than 100 collections per database when running againstMongoDB version 2.6.
func (*Database)ReadConcern¶added inv0.0.13
func (db *Database) ReadConcern() *readconcern.ReadConcern
ReadConcern returns the read concern used to configure the Database object.
func (*Database)ReadPreference¶added inv0.0.13
ReadPreference returns the read preference used to configure the Database object.
func (*Database)RunCommand¶
func (db *Database) RunCommand(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
RunCommand executes the given command against the database.
This function does not obey the Database's readPreference. To specify a readpreference, the RunCmdOptions.ReadPreference option must be used.
This function does not obey the Database's readConcern or writeConcern. Auser must supply these values manually in the user-provided runCommandparameter.
The runCommand parameter must be a document for the command to be executed. It cannot be nil.This must be an order-preserving type such as bson.D. Map types such as bson.M are not valid.
The opts parameter can be used to specify options for this operation (see the options.RunCmdOptions documentation).
The behavior of RunCommand is undefined if the command document contains any of the following:- A session ID or any transaction-specific fields- API versioning options when an API version is already declared on the Client- maxTimeMS when Timeout is set on the Client
Example¶
package mainimport ("context""fmt""log""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readpref")func main() {var db *mongo.Database// Run an explain command to see the query plan for when a "find" is// executed on collection "bar" specify the ReadPreference option to// explicitly set the read preference to primary.findCmd := bson.D{{"find", "bar"}}command := bson.D{{"explain", findCmd}}opts := options.RunCmd().SetReadPreference(readpref.Primary())var result bson.Merr := db.RunCommand(context.TODO(), command, opts).Decode(&result)if err != nil {log.Panic(err)}fmt.Println(result)}func (*Database)RunCommandCursor¶added inv0.1.0
func (db *Database) RunCommandCursor(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor,error)
RunCommandCursor executes the given command against the database and parses the response as a cursor. If the commandbeing executed does not return a cursor (e.g. insert), the command will be executed on the server and an error willbe returned because the server response cannot be parsed as a cursor. This function does not obey the Database's readpreference. To specify a read preference, the RunCmdOptions.ReadPreference option must be used.
The runCommand parameter must be a document for the command to be executed. It cannot be nil.This must be an order-preserving type such as bson.D. Map types such as bson.M are not valid.
The opts parameter can be used to specify options for this operation (see the options.RunCmdOptions documentation).
The behavior of RunCommandCursor is undefined if the command document contains any of the following:- A session ID or any transaction-specific fields- API versioning options when an API version is already declared on the Client- maxTimeMS when Timeout is set on the Client
func (*Database)Watch¶added inv0.1.0
func (db *Database) Watch(ctxcontext.Context, pipeline interface{},opts ...*options.ChangeStreamOptions) (*ChangeStream,error)
Watch returns a change stream for all changes to the corresponding database. Seehttps://www.mongodb.com/docs/manual/changeStreams/ for more information about change streams.
The Database must be configured with read concern majority or no read concern for a change stream to be createdsuccessfully.
The pipeline parameter must be a slice of documents, each representing a pipeline stage. The pipeline cannot benil but can be empty. The stage documents must all be non-nil. Seehttps://www.mongodb.com/docs/manual/changeStreams/ fora list of pipeline stages that can be used with change streams. For a pipeline of bson.D documents, themongo.Pipeline{} type can be used.
The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptionsdocumentation).
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var db *mongo.Database// Specify a pipeline that will only match "insert" events.// Specify the MaxAwaitTimeOption to have each attempt wait two seconds for// new documents.matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)changeStream, err := db.Watch(context.TODO(),mongo.Pipeline{matchStage},opts)if err != nil {log.Panic(err)}// Print out all change stream events in the order they're received.// See the mongo.ChangeStream documentation for more examples of using// change streamsfor changeStream.Next(context.TODO()) {fmt.Println(changeStream.Current)}}func (*Database)WriteConcern¶added inv0.0.13
func (db *Database) WriteConcern() *writeconcern.WriteConcern
WriteConcern returns the write concern used to configure the Database object.
typeDatabaseSpecification¶added inv0.0.3
type DatabaseSpecification struct {Namestring// The name of the database.SizeOnDiskint64// The total size of the database files on disk in bytes.Emptybool// Specifies whether or not the database is empty.}DatabaseSpecification contains information for a database. This type is returned as part of ListDatabasesResult.
typeDeleteManyModel¶added inv0.0.16
DeleteManyModel is used to delete multiple documents in a BulkWrite operation.
funcNewDeleteManyModel¶added inv0.0.16
func NewDeleteManyModel() *DeleteManyModel
NewDeleteManyModel creates a new DeleteManyModel.
func (*DeleteManyModel)SetCollation¶added inv0.3.0
func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteManyModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will beused.
func (*DeleteManyModel)SetFilter¶added inv0.3.0
func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel
SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing queryoperators. It cannot be nil.
func (*DeleteManyModel)SetHint¶added inv1.4.0
func (dmm *DeleteManyModel) SetHint(hint interface{}) *DeleteManyModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the indexspecification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 willreturn an error if this option is specified. For server versions < 3.4, the driver will return a client-side error ifthis option is specified. The driver will return an error if this option is specified during an unacknowledged writeoperation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, whichmeans that no hint will be sent.
typeDeleteOneModel¶added inv0.0.16
DeleteOneModel is used to delete at most one document in a BulkWriteOperation.
funcNewDeleteOneModel¶added inv0.0.16
func NewDeleteOneModel() *DeleteOneModel
NewDeleteOneModel creates a new DeleteOneModel.
func (*DeleteOneModel)SetCollation¶added inv0.3.0
func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will beused.
func (*DeleteOneModel)SetFilter¶added inv0.3.0
func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel
SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing queryoperators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matchingdocuments.
func (*DeleteOneModel)SetHint¶added inv1.4.0
func (dom *DeleteOneModel) SetHint(hint interface{}) *DeleteOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the indexspecification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 willreturn an error if this option is specified. For server versions < 3.4, the driver will return a client-side error ifthis option is specified. The driver will return an error if this option is specified during an unacknowledged writeoperation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, whichmeans that no hint will be sent.
typeDeleteResult¶
type DeleteResult struct {DeletedCountint64 `bson:"n"`// The number of documents deleted.}DeleteResult is the result type returned by DeleteOne and DeleteMany operations.
typeEncryptionKeyVaultError¶added inv1.2.0
type EncryptionKeyVaultError struct {Wrappederror}EncryptionKeyVaultError represents an error while communicating with the key vault collection during client-sideencryption.
func (EncryptionKeyVaultError)Error¶added inv1.2.0
func (ekveEncryptionKeyVaultError) Error()string
Error implements the error interface.
func (EncryptionKeyVaultError)Unwrap¶added inv1.4.0
func (ekveEncryptionKeyVaultError) Unwrap()error
Unwrap returns the underlying error.
typeErrMapForOrderedArgument¶added inv1.5.0
type ErrMapForOrderedArgument struct {ParamNamestring}ErrMapForOrderedArgument is returned when a map with multiple keys is passed to a CRUD method for an ordered parameter
func (ErrMapForOrderedArgument)Error¶added inv1.5.0
func (eErrMapForOrderedArgument) Error()string
Error implements the error interface.
typeIndexModel¶added inv0.0.3
type IndexModel struct {// A document describing which keys should be used for the index. It cannot be nil. This must be an order-preserving// type such as bson.D. Map types such as bson.M are not valid. Seehttps://www.mongodb.com/docs/manual/indexes/#indexes// for examples of valid documents.Keys interface{}// The options to use to create the index.Options *options.IndexOptions}IndexModel represents a new index to be created.
typeIndexOptionsBuilderdeprecatedadded inv0.0.7
type IndexOptionsBuilder struct {// contains filtered or unexported fields}IndexOptionsBuilder specifies options for a new index.
Deprecated: Use the IndexOptions type in the mongo/options package instead.
funcNewIndexOptionsBuilderdeprecatedadded inv0.0.7
func NewIndexOptionsBuilder() *IndexOptionsBuilder
NewIndexOptionsBuilder creates a new IndexOptionsBuilder.
Deprecated: Use the Index function in mongo/options instead.
func (*IndexOptionsBuilder)Backgrounddeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Background(backgroundbool) *IndexOptionsBuilder
Background specifies a value for the background option.
Deprecated: Use the IndexOptions.SetBackground function in mongo/options instead.
func (*IndexOptionsBuilder)Bitsdeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Bits(bitsint32) *IndexOptionsBuilder
Bits specifies a value for the bits option.
Deprecated: Use the IndexOptions.SetBits function in mongo/options instead.
func (*IndexOptionsBuilder)BucketSizedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) BucketSize(bucketSizeint32) *IndexOptionsBuilder
BucketSize specifies a value for the bucketSize option.
Deprecated: Use the IndexOptions.SetBucketSize function in mongo/options instead.
func (*IndexOptionsBuilder)Builddeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Build()bson.D
Build finishes constructing an the builder.
Deprecated: Use the IndexOptions type in the mongo/options package instead.
func (*IndexOptionsBuilder)Collationdeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilder
Collation specifies a value for the collation option.
Deprecated: Use the IndexOptions.SetCollation function in mongo/options instead.
func (*IndexOptionsBuilder)DefaultLanguagedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguagestring) *IndexOptionsBuilder
DefaultLanguage specifies a value for the default_language option.
Deprecated: Use the IndexOptions.SetDefaultLanguage function in mongo/options instead.
func (*IndexOptionsBuilder)ExpireAfterSecondsdeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSecondsint32) *IndexOptionsBuilder
ExpireAfterSeconds specifies a value for the expireAfterSeconds option.
Deprecated: Use the IndexOptions.SetExpireAfterSeconds function in mongo/options instead.
func (*IndexOptionsBuilder)LanguageOverridedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) LanguageOverride(languageOverridestring) *IndexOptionsBuilder
LanguageOverride specifies a value for the language_override option.
Deprecated: Use the IndexOptions.SetLanguageOverride function in mongo/options instead.
func (*IndexOptionsBuilder)Maxdeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Max(maxfloat64) *IndexOptionsBuilder
Max specifies a value for the max option.
Deprecated: Use the IndexOptions.SetMax function in mongo/options instead.
func (*IndexOptionsBuilder)Mindeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Min(minfloat64) *IndexOptionsBuilder
Min specifies a value for the min option.
Deprecated: Use the IndexOptions.SetMin function in mongo/options instead.
func (*IndexOptionsBuilder)Namedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Name(namestring) *IndexOptionsBuilder
Name specifies a value for the name option.
Deprecated: Use the IndexOptions.SetName function in mongo/options instead.
func (*IndexOptionsBuilder)PartialFilterExpressiondeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilder
PartialFilterExpression specifies a value for the partialFilterExpression option.
Deprecated: Use the IndexOptions.SetPartialFilterExpression function in mongo/options instead.
func (*IndexOptionsBuilder)Sparsedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Sparse(sparsebool) *IndexOptionsBuilder
Sparse specifies a value for the sparse option.
Deprecated: Use the IndexOptions.SetSparse function in mongo/options instead.
func (*IndexOptionsBuilder)SphereVersiondeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) SphereVersion(sphereVersionint32) *IndexOptionsBuilder
SphereVersion specifies a value for the 2dsphereIndexVersion option.
Deprecated: Use the IndexOptions.SetSphereVersion function in mongo/options instead.
func (*IndexOptionsBuilder)StorageEnginedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilder
StorageEngine specifies a value for the storageEngine option.
Deprecated: Use the IndexOptions.SetStorageEngine function in mongo/options instead.
func (*IndexOptionsBuilder)TextVersiondeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) TextVersion(textVersionint32) *IndexOptionsBuilder
TextVersion specifies a value for the textIndexVersion option.
Deprecated: Use the IndexOptions.SetTextVersion function in mongo/options instead.
func (*IndexOptionsBuilder)Uniquedeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Unique(uniquebool) *IndexOptionsBuilder
Unique specifies a value for the unique option.
Deprecated: Use the IndexOptions.SetUnique function in mongo/options instead.
func (*IndexOptionsBuilder)Versiondeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Version(versionint32) *IndexOptionsBuilder
Version specifies a value for the version option.
Deprecated: Use the IndexOptions.SetVersion function in mongo/options instead.
func (*IndexOptionsBuilder)Weightsdeprecatedadded inv0.0.7
func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilder
Weights specifies a value for the weights option.
Deprecated: Use the IndexOptions.SetWeights function in mongo/options instead.
typeIndexSpecification¶added inv1.5.0
type IndexSpecification struct {// The index name.Namestring// The namespace for the index. This is a string in the format "databaseName.collectionName".Namespacestring// The keys specification document for the index.KeysDocumentbson.Raw// The index version.Versionint32// The length of time, in seconds, for documents to remain in the collection. The default value is 0, which means// that documents will remain in the collection until they're explicitly deleted or the collection is dropped.ExpireAfterSeconds *int32// If true, the index will only reference documents that contain the fields specified in the index. The default is// false.Sparse *bool// If true, the collection will not accept insertion or update of documents where the index key value matches an// existing value in the index. The default is false.Unique *bool// The clustered index.Clustered *bool}IndexSpecification represents an index in a database. This type is returned by the IndexView.ListSpecificationsfunction and is also used in the CollectionSpecification type.
func (*IndexSpecification)UnmarshalBSONdeprecatedadded inv1.5.0
func (i *IndexSpecification) UnmarshalBSON(data []byte)error
UnmarshalBSON implements the bson.Unmarshaler interface.
Deprecated: Unmarshaling an IndexSpecification from BSON will not be supported in Go Driver 2.0.
typeIndexView¶added inv0.0.3
type IndexView struct {// contains filtered or unexported fields}IndexView is a type that can be used to create, drop, and list indexes on a collection. An IndexView for a collectioncan be created by a call to Collection.Indexes().
func (IndexView)CreateMany¶added inv0.0.3
func (ivIndexView) CreateMany(ctxcontext.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string,error)
CreateMany executes a createIndexes command to create multiple indexes on the collection and returns the names ofthe new indexes.
For each IndexModel in the models parameter, the index name can be specified via the Options field. If a name is notgiven, it will be generated from the Keys document.
The opts parameter can be used to specify options for this operation (see the options.CreateIndexesOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/createIndexes/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var indexView *mongo.IndexView// Create two indexes: {name: 1, email: 1} and {name: 1, age: 1}// For the first index, specify no options. The name will be generated as// "name_1_email_1" by the driver.// For the second index, specify the Name option to explicitly set the name// to "nameAge".models := []mongo.IndexModel{{Keys: bson.D{{"name", 1}, {"email", 1}},},{Keys: bson.D{{"name", 1}, {"age", 1}},Options: options.Index().SetName("nameAge"),},}// Specify the MaxTime option to limit the amount of time the operation can// run on the serveropts := options.CreateIndexes().SetMaxTime(2 * time.Second)names, err := indexView.CreateMany(context.TODO(), models, opts)if err != nil {log.Panic(err)}fmt.Printf("created indexes %v\n", names)}func (IndexView)CreateOne¶added inv0.0.3
func (ivIndexView) CreateOne(ctxcontext.Context, modelIndexModel, opts ...*options.CreateIndexesOptions) (string,error)
CreateOne executes a createIndexes command to create an index on the collection and returns the name of the newindex. See the IndexView.CreateMany documentation for more information and an example.
func (IndexView)DropAll¶added inv0.0.3
func (ivIndexView) DropAll(ctxcontext.Context, opts ...*options.DropIndexesOptions) (bson.Raw,error)
DropAll executes a dropIndexes operation to drop all indexes on the collection. If the operation succeeds, thisreturns a BSON document in the form {nIndexesWas: <int32>}. The "nIndexesWas" field in the response contains thenumber of indexes that existed prior to the drop.
The opts parameter can be used to specify options for this operation (see the options.DropIndexesOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/dropIndexes/.
func (IndexView)DropOne¶added inv0.0.3
func (ivIndexView) DropOne(ctxcontext.Context, namestring, opts ...*options.DropIndexesOptions) (bson.Raw,error)
DropOne executes a dropIndexes operation to drop an index on the collection. If the operation succeeds, this returnsa BSON document in the form {nIndexesWas: <int32>}. The "nIndexesWas" field in the response contains the number ofindexes that existed prior to the drop.
The name parameter should be the name of the index to drop. If the name is "*", ErrMultipleIndexDrop will be returnedwithout running the command because doing so would drop all indexes.
The opts parameter can be used to specify options for this operation (see the options.DropIndexesOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/dropIndexes/.
func (IndexView)DropOneWithKey¶added inv1.17.0
func (ivIndexView) DropOneWithKey(ctxcontext.Context, keySpecDocument interface{}, opts ...*options.DropIndexesOptions) (bson.Raw,error)
DropOneWithKey drops a collection index by key using the dropIndexes operation. If the operation succeeds, this returnsa BSON document in the form {nIndexesWas: <int32>}. The "nIndexesWas" field in the response contains the number ofindexes that existed prior to the drop.
This function is useful to drop an index using its key specification instead of its name.
func (IndexView)List¶added inv0.0.3
List executes a listIndexes command and returns a cursor over the indexes in the collection.
The opts parameter can be used to specify options for this operation (see the options.ListIndexesOptionsdocumentation).
For more information about the command, seehttps://www.mongodb.com/docs/manual/reference/command/listIndexes/.
Example¶
package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {var indexView *mongo.IndexView// Specify the MaxTime option to limit the amount of time the operation can// run on the serveropts := options.ListIndexes().SetMaxTime(2 * time.Second)cursor, err := indexView.List(context.TODO(), opts)if err != nil {log.Panic(err)}// Get a slice of all indexes returned and print them out.var results []bson.Mif err = cursor.All(context.TODO(), &results); err != nil {log.Panic(err)}fmt.Println(results)}func (IndexView)ListSpecifications¶added inv1.5.0
func (ivIndexView) ListSpecifications(ctxcontext.Context, opts ...*options.ListIndexesOptions) ([]*IndexSpecification,error)
ListSpecifications executes a List command and returns a slice of returned IndexSpecifications
typeInsertManyResult¶
type InsertManyResult struct {// The _id values of the inserted documents. Values generated by the driver will be of type primitive.ObjectID.InsertedIDs []interface{}}InsertManyResult is a result type returned by an InsertMany operation.
typeInsertOneModel¶added inv0.0.16
type InsertOneModel struct {Document interface{}}InsertOneModel is used to insert a single document in a BulkWrite operation.
funcNewInsertOneModel¶added inv0.0.16
func NewInsertOneModel() *InsertOneModel
NewInsertOneModel creates a new InsertOneModel.
func (*InsertOneModel)SetDocument¶added inv0.3.0
func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel
SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field whentransformed into BSON, one will be added automatically to the marshalled document. The original document will not bemodified.
typeInsertOneResult¶
type InsertOneResult struct {// The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID.InsertedID interface{}}InsertOneResult is the result type returned by an InsertOne operation.
typeLabeledError¶added inv1.11.4
type LabeledError interface {error// HasErrorLabel returns true if the error contains the specified label.HasErrorLabel(string)bool}LabeledError is an interface for errors with labels.
typeListDatabasesResult¶added inv0.0.3
type ListDatabasesResult struct {// A slice containing one DatabaseSpecification for each database matched by the operation's filter.Databases []DatabaseSpecification// The total size of the database files of the returned databases in bytes.// This will be the sum of the SizeOnDisk field for each specification in Databases.TotalSizeint64}ListDatabasesResult is a result of a ListDatabases operation.
typeMarshalError¶added inv0.0.15
type MarshalError struct {Value interface{}Errerror}MarshalError is returned when attempting to marshal a value into a documentresults in an error.
func (MarshalError)Error¶added inv0.0.15
func (meMarshalError) Error()string
Error implements the error interface.
typeMongocryptError¶added inv1.2.0
MongocryptError represents an libmongocrypt error during client-side encryption.
func (MongocryptError)Error¶added inv1.2.0
func (mMongocryptError) Error()string
Error implements the error interface.
typeMongocryptdError¶added inv1.2.0
type MongocryptdError struct {Wrappederror}MongocryptdError represents an error while communicating with mongocryptd during client-side encryption.
func (MongocryptdError)Error¶added inv1.2.0
func (eMongocryptdError) Error()string
Error implements the error interface.
func (MongocryptdError)Unwrap¶added inv1.4.0
func (eMongocryptdError) Unwrap()error
Unwrap returns the underlying error.
typePipeline¶added inv0.0.18
Pipeline is a type that makes creating aggregation pipelines easier. It is ahelper and is intended for serializing to BSON.
Example usage:
mongo.Pipeline{{{"$group", bson.D{{"_id", "$state"}, {"totalPop", bson.D{{"$sum", "$pop"}}}}}},{{"$match", bson.D{{"totalPop", bson.D{{"$gte", 10*1000*1000}}}}}},}typeReplaceOneModel¶added inv0.0.16
type ReplaceOneModel struct {Collation *options.CollationUpsert *boolFilter interface{}Replacement interface{}Hint interface{}}ReplaceOneModel is used to replace at most one document in a BulkWrite operation.
funcNewReplaceOneModel¶added inv0.0.16
func NewReplaceOneModel() *ReplaceOneModel
NewReplaceOneModel creates a new ReplaceOneModel.
func (*ReplaceOneModel)SetCollation¶added inv0.3.0
func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will beused.
func (*ReplaceOneModel)SetFilter¶added inv0.3.0
func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel
SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing queryoperators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matchingdocuments.
func (*ReplaceOneModel)SetHint¶added inv1.4.0
func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the indexspecification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 willreturn an error if this option is specified. For server versions < 3.4, the driver will return a client-side error ifthis option is specified. The driver will return an error if this option is specified during an unacknowledged writeoperation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, whichmeans that no hint will be sent.
func (*ReplaceOneModel)SetReplacement¶added inv0.3.0
func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel
SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannotcontain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/).
func (*ReplaceOneModel)SetUpsert¶added inv0.3.0
func (rom *ReplaceOneModel) SetUpsert(upsertbool) *ReplaceOneModel
SetUpsert specifies whether or not the replacement document should be inserted if no document matching the filter isfound. If an upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of theBulkWriteResult.
typeRewrapManyDataKeyResult¶added inv1.10.0
type RewrapManyDataKeyResult struct {*BulkWriteResult}RewrapManyDataKeyResult is the result of the bulk write operation used to update the key vault collection withrewrapped data keys.
typeSearchIndexModel¶added inv1.13.0
type SearchIndexModel struct {// A document describing the definition for the search index. It cannot be nil.// Seehttps://www.mongodb.com/docs/atlas/atlas-search/create-index/ for reference.Definition interface{}// The search index options.Options *options.SearchIndexesOptions}SearchIndexModel represents a new search index to be created.
typeSearchIndexView¶added inv1.13.0
type SearchIndexView struct {// contains filtered or unexported fields}SearchIndexView is a type that can be used to create, drop, list and update search indexes on a collection. A SearchIndexView fora collection can be created by a call to Collection.SearchIndexes().
func (SearchIndexView)CreateMany¶added inv1.13.0
func (sivSearchIndexView) CreateMany(ctxcontext.Context,models []SearchIndexModel,_ ...*options.CreateSearchIndexesOptions,) ([]string,error)
CreateMany executes a createSearchIndexes command to create multiple search indexes on the collection and returnsthe names of the new search indexes.
For each SearchIndexModel in the models parameter, the index name can be specified.
The opts parameter can be used to specify options for this operation (see the options.CreateSearchIndexesOptionsdocumentation).
func (SearchIndexView)CreateOne¶added inv1.13.0
func (sivSearchIndexView) CreateOne(ctxcontext.Context,modelSearchIndexModel,opts ...*options.CreateSearchIndexesOptions,) (string,error)
CreateOne executes a createSearchIndexes command to create a search index on the collection and returns the name of the newsearch index. See the SearchIndexView.CreateMany documentation for more information and an example.
func (SearchIndexView)DropOne¶added inv1.13.0
func (sivSearchIndexView) DropOne(ctxcontext.Context,namestring,_ ...*options.DropSearchIndexOptions,)error
DropOne executes a dropSearchIndexes operation to drop a search index on the collection.
The name parameter should be the name of the search index to drop. If the name is "*", ErrMultipleIndexDrop will be returnedwithout running the command because doing so would drop all search indexes.
The opts parameter can be used to specify options for this operation (see the options.DropSearchIndexOptionsdocumentation).
func (SearchIndexView)List¶added inv1.13.0
func (sivSearchIndexView) List(ctxcontext.Context,searchIdxOpts *options.SearchIndexesOptions,opts ...*options.ListSearchIndexesOptions,) (*Cursor,error)
List executes a listSearchIndexes command and returns a cursor over the search indexes in the collection.
The name parameter specifies the index name. A nil pointer matches all indexes.
The opts parameter can be used to specify options for this operation (see the options.ListSearchIndexesOptionsdocumentation).
func (SearchIndexView)UpdateOne¶added inv1.13.0
func (sivSearchIndexView) UpdateOne(ctxcontext.Context,namestring,definition interface{},_ ...*options.UpdateSearchIndexOptions,)error
UpdateOne executes a updateSearchIndex operation to update a search index on the collection.
The name parameter should be the name of the search index to update.
The definition parameter is a document describing the definition for the search index. It cannot be nil.
The opts parameter can be used to specify options for this operation (see the options.UpdateSearchIndexOptionsdocumentation).
typeServerError¶added inv1.5.0
type ServerError interface {LabeledError// HasErrorCode returns true if the error has the specified code.HasErrorCode(int)bool// HasErrorMessage returns true if the error contains the specified message.HasErrorMessage(string)bool// HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message.HasErrorCodeWithMessage(int,string)bool// contains filtered or unexported methods}ServerError is the interface implemented by errors returned from the server. Custom implementations of thisinterface should not be used in production.
typeSession¶added inv0.0.10
type Session interface {// StartTransaction starts a new transaction, configured with the given options, on this// session. This method returns an error if there is already a transaction in-progress for this// session.StartTransaction(...*options.TransactionOptions)error// AbortTransaction aborts the active transaction for this session. This method returns an error// if there is no active transaction for this session or if the transaction has been committed// or aborted.AbortTransaction(context.Context)error// CommitTransaction commits the active transaction for this session. This method returns an// error if there is no active transaction for this session or if the transaction has been// aborted.CommitTransaction(context.Context)error// WithTransaction starts a transaction on this session and runs the fn callback. Errors with// the TransientTransactionError and UnknownTransactionCommitResult labels are retried for up to// 120 seconds. Inside the callback, the SessionContext must be used as the Context parameter// for any operations that should be part of the transaction. If the ctx parameter already has a// Session attached to it, it will be replaced by this session. The fn callback may be run// multiple times during WithTransaction due to retry attempts, so it must be idempotent.// Non-retryable operation errors or any operation errors that occur after the timeout expires// will be returned without retrying. If the callback fails, the driver will call// AbortTransaction. Because this method must succeed to ensure that server-side resources are// properly cleaned up, context deadlines and cancellations will not be respected during this// call. For a usage example, see the Client.StartSession method documentation.WithTransaction(ctxcontext.Context, fn func(ctxSessionContext) (interface{},error),opts ...*options.TransactionOptions) (interface{},error)// EndSession aborts any existing transactions and close the session.EndSession(context.Context)// ClusterTime returns the current cluster time document associated with the session.ClusterTime()bson.Raw// OperationTime returns the current operation time document associated with the session.OperationTime() *primitive.Timestamp// Client the Client associated with the session.Client() *Client// ID returns the current ID document associated with the session. The ID document is in the// form {"id": <BSON binary value>}.ID()bson.Raw// AdvanceClusterTime advances the cluster time for a session. This method returns an error if// the session has ended.AdvanceClusterTime(bson.Raw)error// AdvanceOperationTime advances the operation time for a session. This method returns an error// if the session has ended.AdvanceOperationTime(*primitive.Timestamp)error// contains filtered or unexported methods}Session is an interface that represents a MongoDB logical session. Sessions can be used to enable causal consistencyfor a group of operations or to execute operations in an ACID transaction. A new Session can be created from a Clientinstance. A Session created from a Client must only be used to execute operations using that Client or a Database orCollection created from that Client. Custom implementations of this interface should not be used in production. Formore information about sessions, and their use cases, seehttps://www.mongodb.com/docs/manual/reference/server-sessions/,https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency/#causal-consistency, andhttps://www.mongodb.com/docs/manual/core/transactions/.
Implementations of Session are not safe for concurrent use by multiple goroutines.
funcSessionFromContext¶added inv1.4.0
SessionFromContext extracts the mongo.Session object stored in a Context. This can be used on a SessionContext thatwas created implicitly through one of the callback-based session APIs or explicitly by calling NewSessionContext. Ifthere is no Session stored in the provided Context, nil is returned.
typeSessionContext¶added inv0.0.16
SessionContext combines the context.Context and mongo.Session interfaces. It should be used as the Context argumentsto operations that should be executed in a session.
Implementations of SessionContext are not safe for concurrent use by multiple goroutines.
There are two ways to create a SessionContext and use it in a session/transaction. The first is to use one of thecallback-based functions such as WithSession and UseSession. These functions create a SessionContext and pass it tothe provided callback. The other is to use NewSessionContext to explicitly create a SessionContext.
funcNewSessionContext¶added inv1.4.0
func NewSessionContext(ctxcontext.Context, sessSession)SessionContext
NewSessionContext creates a new SessionContext associated with the given Context and Session parameters.
Example¶
package mainimport ("context""fmt""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo")func main() {var client *mongo.Client// Create a new Session and SessionContext.sess, err := client.StartSession()if err != nil {panic(err)}defer sess.EndSession(context.TODO())ctx := mongo.NewSessionContext(context.TODO(), sess)// Start a transaction and use the mongo.SessionContext as the Context// parameter for InsertOne and FindOne so both operations are run in the// transaction.if err = sess.StartTransaction(); err != nil {panic(err)}coll := client.Database("db").Collection("coll")res, err := coll.InsertOne(ctx, bson.D{{"x", 1}})if err != nil {// Abort the transaction after an error. Use context.Background() to// ensure that the abort can complete successfully even if the context// passed to NewSessionContext is changed to have a timeout._ = sess.AbortTransaction(context.Background())panic(err)}var result bson.Merr = coll.FindOne(ctx,bson.D{{"_id", res.InsertedID}},).Decode(&result)if err != nil {// Abort the transaction after an error. Use context.Background() to// ensure that the abort can complete successfully even if the context// passed to NewSessionContext is changed to have a timeout._ = sess.AbortTransaction(context.Background())panic(err)}fmt.Printf("result: %v\n", result)// Commit the transaction so the inserted document will be stored. Use// context.Background() to ensure that the commit can complete successfully// even if the context passed to NewSessionContext is changed to have a// timeout.if err = sess.CommitTransaction(context.Background()); err != nil {panic(err)}}typeSingleResult¶added inv0.1.0
type SingleResult struct {// contains filtered or unexported fields}SingleResult represents a single document returned from an operation. If the operation resulted in an error, allSingleResult methods will return that error. If the operation did not return any documents, all SingleResult methodswill return ErrNoDocuments.
funcNewSingleResultFromDocument¶added inv1.9.0
func NewSingleResultFromDocument(document interface{}, errerror, registry *bsoncodec.Registry) *SingleResultNewSingleResultFromDocument creates a SingleResult with the provided error, registry, and an underlying Cursor pre-loaded withthe provided document, error and registry. If no registry is provided, bson.DefaultRegistry will be used. If an error distinctfrom the one provided occurs during creation of the SingleResult, that error will be stored on the returned SingleResult.
The document parameter must be a non-nil document.
func (*SingleResult)Decode¶added inv0.1.0
func (sr *SingleResult) Decode(v interface{})error
Decode will unmarshal the document represented by this SingleResult into v. If there was an error from the operationthat created this SingleResult, that error will be returned. If the operation returned no documents, Decode willreturn ErrNoDocuments.
If the operation was successful and returned a document, Decode will return any errors from the unmarshalling processwithout any modification. If v is nil or is a typed nil, an error will be returned.
func (*SingleResult)DecodeBytesdeprecatedadded inv0.1.0
func (sr *SingleResult) DecodeBytes() (bson.Raw,error)
DecodeBytes will return the document represented by this SingleResult as a bson.Raw. If there was an error from theoperation that created this SingleResult, both the result and that error will be returned. If the operation returnedno documents, this will return (nil, ErrNoDocuments).
Deprecated: UseSingleResult.Raw instead.
func (*SingleResult)Err¶added inv0.1.0
func (sr *SingleResult) Err()error
Err provides a way to check for query errors without calling Decode. Err returns the error, ifany, that was encountered while running the operation. If the operation was successful but didnot return any documents, Err returns ErrNoDocuments. If this error is not nil, this error willalso be returned from Decode.
func (*SingleResult)Raw¶added inv1.13.0
func (sr *SingleResult) Raw() (bson.Raw,error)
Raw returns the document represented by this SingleResult as a bson.Raw. Ifthere was an error from the operation that created this SingleResult, boththe result and that error will be returned. If the operation returned nodocuments, this will return (nil, ErrNoDocuments).
typeStreamType¶added inv0.1.0
type StreamTypeuint8
StreamType represents the cluster type against which a ChangeStream was created.
const (CollectionStreamStreamType =iotaDatabaseStreamClientStream)
These constants represent valid change stream types. A change stream can be initialized over a collection, allcollections in a database, or over a cluster.
typeUpdateManyModel¶added inv0.0.16
type UpdateManyModel struct {Collation *options.CollationUpsert *boolFilter interface{}Update interface{}ArrayFilters *options.ArrayFiltersHint interface{}}UpdateManyModel is used to update multiple documents in a BulkWrite operation.
funcNewUpdateManyModel¶added inv0.0.16
func NewUpdateManyModel() *UpdateManyModel
NewUpdateManyModel creates a new UpdateManyModel.
func (*UpdateManyModel)SetArrayFilters¶added inv0.3.0
func (umm *UpdateManyModel) SetArrayFilters(filtersoptions.ArrayFilters) *UpdateManyModel
SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an arrayfield.
func (*UpdateManyModel)SetCollation¶added inv0.3.0
func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will beused.
func (*UpdateManyModel)SetFilter¶added inv0.3.0
func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel
SetFilter specifies a filter to use to select documents to update. The filter must be a document containing queryoperators. It cannot be nil.
func (*UpdateManyModel)SetHint¶added inv1.4.0
func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the indexspecification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 willreturn an error if this option is specified. For server versions < 3.4, the driver will return a client-side error ifthis option is specified. The driver will return an error if this option is specified during an unacknowledged writeoperation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, whichmeans that no hint will be sent.
func (*UpdateManyModel)SetUpdate¶added inv0.3.0
func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel
SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containingupdate operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty.
func (*UpdateManyModel)SetUpsert¶added inv0.3.0
func (umm *UpdateManyModel) SetUpsert(upsertbool) *UpdateManyModel
SetUpsert specifies whether or not a new document should be inserted if no document matching the filter is found. Ifan upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of theBulkWriteResult.
typeUpdateOneModel¶added inv0.0.16
type UpdateOneModel struct {Collation *options.CollationUpsert *boolFilter interface{}Update interface{}ArrayFilters *options.ArrayFiltersHint interface{}}UpdateOneModel is used to update at most one document in a BulkWrite operation.
funcNewUpdateOneModel¶added inv0.0.16
func NewUpdateOneModel() *UpdateOneModel
NewUpdateOneModel creates a new UpdateOneModel.
func (*UpdateOneModel)SetArrayFilters¶added inv0.3.0
func (uom *UpdateOneModel) SetArrayFilters(filtersoptions.ArrayFilters) *UpdateOneModel
SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an arrayfield.
func (*UpdateOneModel)SetCollation¶added inv0.3.0
func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will beused.
func (*UpdateOneModel)SetFilter¶added inv0.3.0
func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel
SetFilter specifies a filter to use to select the document to update. The filter must be a document containing queryoperators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matchingdocuments.
func (*UpdateOneModel)SetHint¶added inv1.4.0
func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the indexspecification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 willreturn an error if this option is specified. For server versions < 3.4, the driver will return a client-side error ifthis option is specified. The driver will return an error if this option is specified during an unacknowledged writeoperation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, whichmeans that no hint will be sent.
func (*UpdateOneModel)SetUpdate¶added inv0.3.0
func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel
SetUpdate specifies the modifications to be made to the selected document. The value must be a document containingupdate operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty.
func (*UpdateOneModel)SetUpsert¶added inv0.3.0
func (uom *UpdateOneModel) SetUpsert(upsertbool) *UpdateOneModel
SetUpsert specifies whether or not a new document should be inserted if no document matching the filter is found. Ifan upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of theBulkWriteResult.
typeUpdateResult¶
type UpdateResult struct {MatchedCountint64// The number of documents matched by the filter.ModifiedCountint64// The number of documents modified by the operation.UpsertedCountint64// The number of documents upserted by the operation.UpsertedID interface{}// The _id field of the upserted document, or nil if no upsert was done.}UpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations.
func (*UpdateResult)UnmarshalBSONdeprecated
func (result *UpdateResult) UnmarshalBSON(b []byte)error
UnmarshalBSON implements the bson.Unmarshaler interface.
Deprecated: Unmarshalling an UpdateResult directly from BSON is not supported and may producedifferent results compared to running Update* operations directly.
typeWriteConcernError¶added inv0.0.4
type WriteConcernError struct {NamestringCodeintMessagestringDetailsbson.RawRawbson.Raw// The original write concern error from the server response.}WriteConcernError represents a write concern failure during execution of a write operation. This error type is onlyreturned as part of a WriteException or a BulkWriteException.
func (WriteConcernError)Error¶added inv0.0.4
func (wceWriteConcernError) Error()string
Error implements the error interface.
func (WriteConcernError)IsMaxTimeMSExpiredError¶added inv1.11.0
func (wceWriteConcernError) IsMaxTimeMSExpiredError()bool
IsMaxTimeMSExpiredError returns true if the error is a MaxTimeMSExpired error.
typeWriteError¶added inv0.0.4
type WriteError struct {// The index of the write in the slice passed to an InsertMany or BulkWrite operation that caused this error.IndexintCodeintMessagestringDetailsbson.Raw// The original write error from the server response.Rawbson.Raw}WriteError is an error that occurred during execution of a write operation. This error type is only returned as partof a WriteException or BulkWriteException.
func (WriteError)Error¶added inv0.0.4
func (weWriteError) Error()string
func (WriteError)HasErrorCode¶added inv1.9.0
func (weWriteError) HasErrorCode(codeint)bool
HasErrorCode returns true if the error has the specified code.
func (WriteError)HasErrorCodeWithMessage¶added inv1.9.0
func (weWriteError) HasErrorCodeWithMessage(codeint, messagestring)bool
HasErrorCodeWithMessage returns true if the error has the specified code and Message contains the specified message.
func (WriteError)HasErrorLabel¶added inv1.9.0
func (weWriteError) HasErrorLabel(string)bool
HasErrorLabel returns true if the error contains the specified label. WriteErrors do not contain labels,so we always return false.
func (WriteError)HasErrorMessage¶added inv1.9.0
func (weWriteError) HasErrorMessage(messagestring)bool
HasErrorMessage returns true if the error contains the specified message.
typeWriteErrors¶added inv0.0.4
type WriteErrors []WriteError
WriteErrors is a group of write errors that occurred during execution of a write operation.
func (WriteErrors)Error¶added inv0.0.4
func (weWriteErrors) Error()string
Error implements the error interface.
typeWriteException¶added inv0.3.0
type WriteException struct {// The write concern error that occurred, or nil if there was none.WriteConcernError *WriteConcernError// The write errors that occurred during operation execution.WriteErrorsWriteErrors// The categories to which the exception belongs.Labels []string// The original server response containing the error.Rawbson.Raw}WriteException is the error type returned by the InsertOne, DeleteOne, DeleteMany, UpdateOne, UpdateMany, andReplaceOne operations.
func (WriteException)Error¶added inv0.3.0
func (mweWriteException) Error()string
Error implements the error interface.
func (WriteException)HasErrorCode¶added inv1.5.0
func (mweWriteException) HasErrorCode(codeint)bool
HasErrorCode returns true if the error has the specified code.
func (WriteException)HasErrorCodeWithMessage¶added inv1.5.0
func (mweWriteException) HasErrorCodeWithMessage(codeint, messagestring)bool
HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message.
func (WriteException)HasErrorLabel¶added inv1.4.0
func (mweWriteException) HasErrorLabel(labelstring)bool
HasErrorLabel returns true if the error contains the specified label.
func (WriteException)HasErrorMessage¶added inv1.5.0
func (mweWriteException) HasErrorMessage(messagestring)bool
HasErrorMessage returns true if the error contains the specified message.
typeWriteModel¶added inv0.0.16
type WriteModel interface {// contains filtered or unexported methods}WriteModel is an interface implemented by models that can be used in a BulkWrite operation. Each WriteModelrepresents a write.
This interface is implemented by InsertOneModel, DeleteOneModel, DeleteManyModel, ReplaceOneModel, UpdateOneModel,and UpdateManyModel. Custom implementations of this interface must not be used.
typeXSessiondeprecatedadded inv1.2.0
XSession is an unstable interface for internal use only.
Deprecated: This interface is unstable because it provides access to a session.Client object, which exists in the"x" package. It should not be used by applications and may be changed or removed in any release.
Notes¶
Bugs¶
ListCollectionSpecifications prevents listing more than 100 collections per database when runningagainst MongoDB version 2.6.
ListCollections prevents listing more than 100 collections per database when running againstMongoDB version 2.6.
ListCollectionNames prevents listing more than 100 collections per database when running againstMongoDB version 2.6.
Source Files¶
- background_context.go
- batch_cursor.go
- bulk_write.go
- bulk_write_models.go
- change_stream.go
- change_stream_deployment.go
- client.go
- client_encryption.go
- collection.go
- crypt_retrievers.go
- cursor.go
- database.go
- doc.go
- errors.go
- index_options_builder.go
- index_view.go
- mongo.go
- mongocryptd.go
- results.go
- search_index_view.go
- session.go
- single_result.go
- util.go
Directories¶
| Path | Synopsis |
|---|---|
Package address provides structured representations of network addresses. | Package address provides structured representations of network addresses. |
Package description contains types and functions for describing the state of MongoDB clusters. | Package description contains types and functions for describing the state of MongoDB clusters. |
Package gridfs provides a MongoDB GridFS API. | Package gridfs provides a MongoDB GridFS API. |
mtest Package mtest is unstable and there is no backward compatibility guarantee. | Package mtest is unstable and there is no backward compatibility guarantee. |
Package options defines the optional configurations for the MongoDB Go Driver. | Package options defines the optional configurations for the MongoDB Go Driver. |
Package readconcern defines read concerns for MongoDB operations. | Package readconcern defines read concerns for MongoDB operations. |
Package readpref defines read preferences for MongoDB queries. | Package readpref defines read preferences for MongoDB queries. |
Package writeconcern defines write concerns for MongoDB operations. | Package writeconcern defines write concerns for MongoDB operations. |