mongo-driver: go.mongodb.org/mongo-driver/mongo Index | Examples | Files | Directories

package mongo

import "go.mongodb.org/mongo-driver/mongo"

Package mongo provides a MongoDB Driver API for Go.

Basic usage of the driver starts with creating a Client from a connection string. To do so, call the NewClient and Connect functions:

client, err := NewClient(options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))
if err != nil { return err }
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
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.InsertedID

Several 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
}

Methods that only return a single document will return a *SingleResult, which works like 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 and on the MongoDB website.

Potential DNS Issues

Building with Go 1.11+ and using connection strings with the "mongodb+srv"[1] scheme is incompatible with some DNS servers in the wild due to the change introduced in https://github.com/golang/go/issues/10622. If you receive an error with the message "cannot unmarshal DNS message" while running an operation, we suggest you use a different DNS server.

Client Side Encryption

Client-side encryption is a new feature in MongoDB 4.2 that allows specific data fields to be encrypted. Using this feature requires specifying the "cse" build tag during compilation.

Note: Auto encryption is an enterprise-only feature.

The libmongocrypt C library is required when using client-side encryption. To install libmongocrypt, follow the instructions for your operating system:

1. Linux: follow the instructions listed at https://github.com/mongodb/libmongocrypt#installing-libmongocrypt-from-distribution-packages to install the correct deb/rpm package.

2. Mac: Follow the instructions listed at https://github.com/mongodb/libmongocrypt#installing-libmongocrypt-on-macos to install packages via brew and compile the libmongocrypt source code.

3. Windows:

mkdir -p c:/libmongocrypt/bin
mkdir -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.gz
tar -xvzf libmongocrypt.tar.gz

cp ./bin/mongocrypt.dll c:/libmongocrypt/bin
cp ./include/mongocrypt/*.h c:/libmongocrypt/include
export PATH=$PATH:/cygdrive/c/libmongocrypt/bin

libmongocrypt communicates with the mongocryptd process for automatic encryption. This process can be started manually or auto-spawned by the driver itself. To enable auto-spawning, ensure the process binary is on the PATH. To start it manually, use AutoEncryptionOptions:

aeo := options.AutoEncryption()
mongocryptdOpts := map[string]interface{}{
    "mongocryptdBypassSpawn": true,
}
aeo.SetExtraOptions(mongocryptdOpts)

To specify a process URI for mongocryptd, the "mongocryptdURI" option can be passed in the ExtraOptions map as well. See the ClientSideEncryption and ClientSideEncryptionCreateKey examples below for code samples about using this feature.

[1] See https://docs.mongodb.com/manual/reference/connection-string/#dns-seedlist-connection-format

Code:

// 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.Fatal(err)
}
kmsProviders := map[string]map[string]interface{}{
    "local": {
        "key": localKey,
    },
}
keyVaultNamespace := "admin.datakeys"

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.Fatalf("Connect error: %v", err)
}
defer func() {
    if err = client.Disconnect(context.TODO()); err != nil {
        log.Fatalf("Disconnect error: %v", err)
    }
}()

collection := client.Database("test").Collection("coll")
if err := collection.Drop(context.TODO()); err != nil {
    log.Fatalf("Collection.Drop error: %v", err)
}

if _, err = collection.InsertOne(context.TODO(), bson.D{{"encryptedField", "123456789"}}); err != nil {
    log.Fatalf("InsertOne error: %v", err)
}
res, err := collection.FindOne(context.TODO(), bson.D{}).DecodeBytes()
if err != nil {
    log.Fatalf("FindOne error: %v", err)
}
fmt.Println(res)

Code:

keyVaultNamespace := "admin.datakeys"
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 ClientEncryption
clientEncryptionOpts := options.ClientEncryption().
    SetKeyVaultNamespace(keyVaultNamespace).
    SetKmsProviders(kmsProviders)
keyVaultClient, err := Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
    log.Fatalf("Connect error for keyVaultClient: %v", err)
}
clientEnc, err := NewClientEncryption(keyVaultClient, clientEncryptionOpts)
if err != nil {
    log.Fatalf("NewClientEncryption error: %v", err)
}
defer func() {
    // this will disconnect the keyVaultClient as well
    if err = clientEnc.Close(context.TODO()); err != nil {
        log.Fatalf("Close error: %v", err)
    }
}()

// Create a new data key and encode it as base64
dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), "local")
if err != nil {
    log.Fatalf("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.Raw
if err = bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc); err != nil {
    log.Fatalf("UnmarshalExtJSON error: %v", err)
}

// Configure a Client with auto encryption using the new schema
dbName := "test"
collName := "coll"
schemaMap := map[string]interface{}{
    dbName + "." + collName: schemaDoc,
}
autoEncryptionOpts := options.AutoEncryption().
    SetKmsProviders(kmsProviders).
    SetKeyVaultNamespace(keyVaultNamespace).
    SetSchemaMap(schemaMap)
client, err := Connect(context.TODO(), options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOpts))
if err != nil {
    log.Fatalf("Connect error for encrypted client: %v", err)
}

// Use client for operations.

if err = client.Disconnect(context.TODO()); err != nil {
    log.Fatalf("Disconnect error: %v", err)
}

Index

Examples

Package Files

batch_cursor.go bulk_write.go bulk_write_models.go change_stream.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 session.go single_result.go util.go

Variables

var ErrClientDisconnected = errors.New("client is disconnected")

ErrClientDisconnected is returned when a user attempts to call a method on a disconnected client

var ErrEmptySlice = errors.New("must provide at least one element in input slice")

ErrEmptySlice is returned when a user attempts to pass an empty slice as input to a function wehere the field is required.

var ErrInvalidIndexValue = errors.New("invalid index value")

ErrInvalidIndexValue indicates that the index Keys document has a value that isn't either a number or a string.

var ErrMissingResumeToken = errors.New("cannot provide resume functionality when the resume token is missing")

ErrMissingResumeToken indicates that a change stream notification from the server did not contain a resume token.

var ErrMultipleIndexDrop = errors.New("multiple indexes would be dropped")

ErrMultipleIndexDrop indicates that multiple indexes would be dropped from a call to IndexView.DropOne.

var ErrNilCursor = errors.New("cursor is nil")

ErrNilCursor indicates that the underlying cursor for the change stream is nil.

var ErrNilDocument = errors.New("document is nil")

ErrNilDocument is returned when a user attempts to pass a nil document or filter to a function where the field is required.

var ErrNoDocuments = errors.New("mongo: no documents in result")

ErrNoDocuments is returned by Decode when an operation that returns a SingleResult doesn't return any documents.

var ErrNonStringIndexName = errors.New("index name must be a string")

ErrNonStringIndexName indicates that the index name specified in the options is not a string.

var ErrUnacknowledgedWrite = errors.New("unacknowledged write")

ErrUnacknowledgedWrite is returned from functions 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 than the method call is using.

func BatchCursorFromCursor Uses

func BatchCursorFromCursor(c *Cursor) *driver.BatchCursor

BatchCursorFromCursor returns a driver.BatchCursor for the given Cursor. If there is no underlying driver.BatchCursor, nil is returned. This method is deprecated and does not have any stability guarantees. It may be removed in the future.

func WithSession Uses

func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error

WithSession creates a new SessionContext from the ctx and sess parameters and uses it to call the fn callback. The SessionContext must be used as the Context parameter for any operations in the fn callback that should be executed under the session.

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.

Code:

var client *mongo.Client // assume client is configured with write concern majority and read preference primary

// 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.Fatal(err)
}
defer sess.EndSession(context.TODO())

// Call WithSession to use the new Session to insert a document and find it.
err = mongo.WithSession(context.TODO(), sess, func(sessCtx mongo.SessionContext) error {
    // Use sessCtx as the Context parameter for InsertOne and FindOne so both operations are run under the new
    // Session.

    coll := client.Database("db").Collection("coll")
    res, err := coll.InsertOne(sessCtx, bson.D{{"x", 1}})
    if err != nil {
        return err
    }

    var result bson.M
    if err = coll.FindOne(sessCtx, bson.D{{"_id", res.InsertedID}}).Decode(result); err != nil {
        return err
    }
    fmt.Println(result)
    return nil
})

type BSONAppender Uses

type BSONAppender interface {
    AppendBSON([]byte, interface{}) ([]byte, error)
}

BSONAppender is an interface implemented by types that can marshal a provided 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 AppendBSON method may also write incomplete BSON to the []byte.

type BSONAppenderFunc Uses

type BSONAppenderFunc func([]byte, interface{}) ([]byte, error)

BSONAppenderFunc is an adapter function that allows any function that satisfies the AppendBSON method signature to be used where a BSONAppender is used.

func (BSONAppenderFunc) AppendBSON Uses

func (baf BSONAppenderFunc) AppendBSON(dst []byte, val interface{}) ([]byte, error)

AppendBSON implements the BSONAppender interface

type BulkWriteError Uses

type BulkWriteError struct {
    WriteError
    Request WriteModel
}

BulkWriteError is an error for one operation in a bulk write.

func (BulkWriteError) Error Uses

func (bwe BulkWriteError) Error() string

type BulkWriteException Uses

type BulkWriteException struct {
    WriteConcernError *WriteConcernError
    WriteErrors       []BulkWriteError
}

BulkWriteException is an error for a bulk write operation.

func (BulkWriteException) Error Uses

func (bwe BulkWriteException) Error() string

type BulkWriteResult Uses

type BulkWriteResult struct {
    InsertedCount int64
    MatchedCount  int64
    ModifiedCount int64
    DeletedCount  int64
    UpsertedCount int64
    UpsertedIDs   map[int64]interface{}
}

BulkWriteResult holds the result of a bulk write operation.

type ChangeStream Uses

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.
    Current bson.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 Decode method or accessed as raw BSON via the Current field. For more information about change streams, see https://docs.mongodb.com/manual/changeStreams/.

func (*ChangeStream) Close Uses

func (cs *ChangeStream) Close(ctx context.Context) error

Close closes this change stream and the underlying cursor. Next and TryNext must not be called after Close has been called. Close is idempotent. After the first call, any subsequent calls will not change the state.

func (*ChangeStream) Decode Uses

func (cs *ChangeStream) Decode(val interface{}) error

Decode will unmarshal the current event document into val and return any errors from the unmarshalling process without any modification. If val is nil or is a typed nil, an error will be returned.

func (*ChangeStream) Err Uses

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 Uses

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 Uses

func (cs *ChangeStream) Next(ctx context.Context) bool

Next gets the next event for this change stream. It returns true if there were no errors and the next event document is available.

Next blocks until an event is available, an error occurs, or ctx expires. If ctx expires, the error will be set to ctx.Err(). In an error case, Next will return false.

If Next returns false, subsequent calls will also return false.

Code:

var stream *mongo.ChangeStream
defer 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.M
    if err := stream.Decode(&event); err != nil {
        log.Fatal(err)
    }
    fmt.Println(event)
}
if err := stream.Err(); err != nil {
    log.Fatal(err)
}

func (*ChangeStream) ResumeToken Uses

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 been stored.

Code:

var client *mongo.Client
var stream *mongo.ChangeStream // assume stream was created via client.Watch()

cancelCtx, cancel := context.WithCancel(context.TODO())
defer cancel()
var wg sync.WaitGroup
wg.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.Client
opts := options.ChangeStream().SetResumeAfter(resumeToken)
newStream, err := newClient.Watch(context.TODO(), mongo.Pipeline{}, opts)
if err != nil {
    log.Fatal(err)
}
defer newStream.Close(context.TODO())

func (*ChangeStream) TryNext Uses

func (cs *ChangeStream) TryNext(ctx context.Context) bool

TryNext attempts to get the next event for this change stream. It returns true if there were no errors and the next event document is available.

TryNext returns false if the change stream is closed by the server, an error occurs when getting changes from the server, 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 call TryNext again until a change is available.

This method requires driver version >= 1.2.0.

Code:

var stream *mongo.ChangeStream
defer 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.M
        if err := stream.Decode(&event); err != nil {
            log.Fatal(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.Fatal(err)
    }
    if stream.ID() == 0 {
        break
    }
}

type Client Uses

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 by multiple goroutines.

The Client type opens and closes connections automatically and maintains a pool of idle connections. For connection pool configuration options, see documentation for the ClientOptions type in the mongo/options package.

Code:

// Create a Client and execute a ListDatabases operation.

client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    log.Fatal(err)
}
defer func() {
    if err = client.Disconnect(context.TODO()); err != nil {
        log.Fatal(err)
    }
}()

collection := client.Database("db").Collection("coll")
result, err := collection.InsertOne(context.TODO(), bson.D{{"x", 1}})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("inserted ID: %v\n", result.InsertedID)

func Connect Uses

func Connect(ctx context.Context, opts ...*options.ClientOptions) (*Client, error)

Connect creates a new Client and then initializes it using the Connect method. This is equivalent to calling NewClient 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 the ApplyURI method. This allows callers to determine the order of precedence for option application. For instance, if ApplyURI is called before SetAuth, the Credential from SetAuth will overwrite the values from the connection string. If ApplyURI is called after SetAuth, then its values will overwrite those from SetAuth.

The opts parameter is processed using options.MergeClientOptions, which will overwrite entire option fields of previous options, there is no partial overwriting. For example, if Username is set in the Auth field for the first option, and Password is set for the second but with no Username, 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 do any I/O in the main goroutine to prevent the main goroutine from blocking. Therefore, it will not error if the deployment is down.

The Client.Ping method can be used to verify that the deployment is successfully connected and the Client was correctly configured.

Code:

// 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.Fatal(err)
}
_ = client

Code:

// Configure a Client with GSSAPI/SSPI authentication (https://docs.mongodb.com/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.Fatal(err)
}
_ = client

Code:

// Configure a Client with LDAP authentication
// (https://docs.mongodb.com/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.Fatal(err)
}
_ = client

Code:

// 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.Fatal(err)
}
defer func() {
    if err = client.Disconnect(context.TODO()); err != nil {
        log.Fatal(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.Fatal(err)
}

Code:

// 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.Fatal(err)
}
_ = client

Code:

// Configure a Client with SCRAM authentication (https://docs.mongodb.com/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.Fatal(err)
}
_ = client

Code:

// 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://docs.mongodb.com/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.Fatal(err)
}
_ = client

Code:

// 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.Fatal(err)
}
_ = client

Code:

// Configure a Client with X509 authentication (https://docs.mongodb.com/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.Fatal(err)
}
_ = client

func NewClient Uses

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 the ApplyURI method. This allows callers to determine the order of precedence for option application. For instance, if ApplyURI is called before SetAuth, the Credential from SetAuth will overwrite the values from the connection string. If ApplyURI is called after SetAuth, then its values will overwrite those from SetAuth.

The opts parameter is processed using options.MergeClientOptions, which will overwrite entire option fields of previous options, there is no partial overwriting. For example, if Username is set in the Auth field for the first option, and Password is set for the second but with no Username, after the merge the Username field will be empty.

func (*Client) Connect Uses

func (c *Client) Connect(ctx context.Context) error

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 main goroutine. The Client.Ping method can be used to verify that the connection was created successfully.

func (*Client) Database Uses

func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database

Database returns a handle for a database with the given name configured with the given DatabaseOptions.

func (*Client) Disconnect Uses

func (c *Client) Disconnect(ctx context.Context) error

Disconnect closes sockets to the topology referenced by this Client. It will shut down any monitoring goroutines, close the idle connection pool, and will wait until all the in use connections have been returned to the connection pool and closed before returning. If the context expires via cancellation, deadline, or timeout before the in use connections have returned, the in use connections will be closed, resulting in the failure of any in flight read or write operations. If this method returns with no errors, all connections associated with this Client have been closed.

func (*Client) ListDatabaseNames Uses

func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error)

ListDatabaseNames executes a listDatabases command and returns a slice containing the names of all of the databases on the server.

The filter parameter must be a document containing query operators and can be used to select which databases are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all databases.

The opts parameter can be used to specify options for this operation (see the options.ListDatabasesOptions documentation.)

For more information about the command, see https://docs.mongodb.com/manual/reference/command/listDatabases/.

Code:

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.Fatal(err)
}

for _, db := range result {
    fmt.Println(db)
}

func (*Client) ListDatabases Uses

func (c *Client) ListDatabases(ctx context.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 which databases are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all databases.

The opts paramter can be used to specify options for this operation (see the options.ListDatabasesOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/listDatabases/.

func (*Client) NumberSessionsInProgress Uses

func (c *Client) NumberSessionsInProgress() int

NumberSessionsInProgress returns the number of sessions that have been started for this client but have not been closed (i.e. EndSession has not been called).

func (*Client) Ping Uses

func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error

Ping sends a ping command to verify that the client can connect to the deployment.

The rp paramter 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 temporarily unavailable or is failing over (e.g. during autoscaling due to a load spike).

func (*Client) StartSession Uses

func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)

StartSession starts a new session configured with the given options.

If the DefaultReadConcern, DefaultWriteConcern, or DefaultReadPreference options are not set, the client's read concern, write concern, or read preference will be used, respectively.

Code:

var client *mongo.Client // assume client is configured with write concern majority and read preference primary

// 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.Fatal(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(sessCtx mongo.SessionContext) (interface{}, error) {
    // Use sessCtx as the Context parameter for InsertOne and FindOne so both operations are run in a
    // transaction.

    coll := client.Database("db").Collection("coll")
    res, err := coll.InsertOne(sessCtx, bson.D{{"x", 1}})
    if err != nil {
        return nil, err
    }

    var result bson.M
    if err = coll.FindOne(sessCtx, bson.D{{"_id", res.InsertedID}}).Decode(result); err != nil {
        return nil, err
    }
    return result, err
}, txnOpts)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("result: %v\n", result)

func (*Client) UseSession Uses

func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error

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 should be executed under a session. After the callback returns, the created Session is ended, meaning that any in-progress transactions started by fn will be aborted even if fn returns an error.

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 Uses

func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, fn func(SessionContext) error) error

UseSessionWithOptions operates like UseSession but uses the given SessionOptions to create the Session.

Code:

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(sessCtx mongo.SessionContext) error {
    // Use sessCtx as the Context parameter for InsertOne and FindOne so both operations are run under the new
    // Session.

    coll := client.Database("db").Collection("coll")
    res, err := coll.InsertOne(sessCtx, bson.D{{"x", 1}})
    if err != nil {
        return err
    }

    var result bson.M
    if err = coll.FindOne(sessCtx, bson.D{{"_id", res.InsertedID}}).Decode(result); err != nil {
        return err
    }
    fmt.Println(result)
    return nil
})
if err != nil {
    log.Fatal(err)
}

func (*Client) Watch Uses

func (c *Client) Watch(ctx context.Context, pipeline interface{},
    opts ...*options.ChangeStreamOptions) (*ChangeStream, error)

Watch returns a change stream for all changes on the deployment. See https://docs.mongodb.com/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 created successfully.

The pipeline parameter must be an array of documents, each representing a pipeline stage. The pipeline cannot be nil or empty. The stage documents must all be non-nil. See https://docs.mongodb.com/manual/changeStreams/ for a list of 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.ChangeStreamOptions documentation).

Code:

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.Fatal(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)
}

type ClientEncryption Uses

type ClientEncryption struct {
    // contains filtered or unexported fields
}

ClientEncryption is used to create data keys and explicitly encrypt and decrypt BSON values.

func NewClientEncryption Uses

func NewClientEncryption(keyVaultClient *Client, opts ...*options.ClientEncryptionOptions) (*ClientEncryption, error)

NewClientEncryption creates a new ClientEncryption instance configured with the given options.

func (*ClientEncryption) Close Uses

func (ce *ClientEncryption) Close(ctx context.Context) error

Close cleans up any resources associated with the ClientEncryption instance. This includes disconnecting the key-vault Client instance.

func (*ClientEncryption) CreateDataKey Uses

func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider string, opts ...*options.DataKeyOptions) (primitive.Binary, error)

CreateDataKey creates a new key document and inserts it into the key vault collection. Returns the _id of the created document.

func (*ClientEncryption) Decrypt Uses

func (ce *ClientEncryption) Decrypt(ctx context.Context, val primitive.Binary) (bson.RawValue, error)

Decrypt decrypts an encrypted value (BSON binary of subtype 6) and returns the original BSON value.

func (*ClientEncryption) Encrypt Uses

func (ce *ClientEncryption) Encrypt(ctx context.Context, val bson.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).

type Collection Uses

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 Uses

func (coll *Collection) Aggregate(ctx context.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 cannot be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, the mongo.Pipeline type can be used. See https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/#db-collection-aggregate-stages for a list of valid 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, see https://docs.mongodb.com/manual/reference/command/aggregate/.

Code:

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.Fatal(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.M
if err = cursor.All(context.TODO(), &results); err != nil {
    log.Fatal(err)
}
for _, result := range results {
    fmt.Printf("name %v appears %v times\n", result["_id"], result["numTimes"])
}

func (*Collection) BulkWrite Uses

func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel,
    opts ...*options.BulkWriteOptions) (*BulkWriteResult, error)

BulkWrite performs a bulk write operation (https://docs.mongodb.com/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 and examples of how they should be used.

The opts parameter can be used to specify options for the operation (see the options.BulkWriteOptions documentation.)

Code:

var coll *mongo.Collection
var 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.Fatal(err)
}

fmt.Printf("inserted %v and deleted %v documents\n", res.InsertedCount, res.DeletedCount)

func (*Collection) Clone Uses

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 taking precedence.

func (*Collection) CountDocuments Uses

func (coll *Collection) CountDocuments(ctx context.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 the collection, see the EstimatedDocumentCount method.

The filter parameter must be a document and can be used to select which documents contribute to the count. It cannot be nil. An empty document (e.g. bson.D{}) should be used to count all documents in the collection. This will result in a full collection scan.

The opts parameter can be used to specify options for the operation (see the options.CountOptions documentation).

Code:

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.Fatal(err)
}
fmt.Printf("name Bob appears in %v documents", count)

func (*Collection) Database Uses

func (coll *Collection) Database() *Database

Database returns the Database that was used to create the Collection.

func (*Collection) DeleteMany Uses

func (coll *Collection) DeleteMany(ctx context.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 parameters and can be used to select the documents to be deleted. It cannot be nil. An empty document (e.g. bson.D{}) should be used to delete all documents in the collection. If the filter does not match any documents, the operation will succeed and a DeleteResult with a DeletedCount 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, see https://docs.mongodb.com/manual/reference/command/delete/.

Code:

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.Fatal(err)
}
fmt.Printf("deleted %v documents\n", res.DeletedCount)

func (*Collection) DeleteOne Uses

func (coll *Collection) DeleteOne(ctx context.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 parameters and can be used to select the document to be deleted. It cannot be nil. If the filter does not match any documents, the operation will succeed and a DeleteResult with a DeletedCount of 0 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 the operation (see the options.DeleteOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/delete/.

Code:

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.Fatal(err)
}
fmt.Printf("deleted %v documents\n", res.DeletedCount)

func (*Collection) Distinct Uses

func (coll *Collection) Distinct(ctx context.Context, fieldName string, 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 are considered. 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, see https://docs.mongodb.com/manual/reference/command/distinct/.

Code:

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.Fatal(err)
}

for _, value := range values {
    fmt.Println(value)
}

func (*Collection) Drop Uses

func (coll *Collection) Drop(ctx context.Context) error

Drop drops the collection on the server. This method ignores "namespace not found" errors so it is safe to drop a collection that does not exist on the server.

func (*Collection) EstimatedDocumentCount Uses

func (coll *Collection) EstimatedDocumentCount(ctx context.Context,
    opts ...*options.EstimatedDocumentCountOptions) (int64, error)

EstimatedDocumentCount executes a count command and returns an estimate of the number of documents in the collection using collection metadata.

The opts parameter can be used to specify options for the operation (see the options.EstimatedDocumentCountOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/count/.

Code:

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.Fatal(err)
}
fmt.Printf("estimated document count: %v", count)

func (*Collection) Find Uses

func (coll *Collection) Find(ctx context.Context, filter interface{},
    opts ...*options.FindOptions) (*Cursor, error)

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 are included 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, see https://docs.mongodb.com/manual/reference/command/find/.

Code:

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.Fatal(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.M
if err = cursor.All(context.TODO(), &results); err != nil {
    log.Fatal(err)
}
for _, result := range results {
    fmt.Println(result)
}

func (*Collection) FindOne Uses

func (coll *Collection) FindOne(ctx context.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 be returned. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set to ErrNoDocuments 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, see https://docs.mongodb.com/manual/reference/command/find/.

Code:

var coll *mongo.Collection
var 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.M
err := 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 err == mongo.ErrNoDocuments {
        return
    }
    log.Fatal(err)
}
fmt.Printf("found document %v", result)

func (*Collection) FindOneAndDelete Uses

func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{},
    opts ...*options.FindOneAndDeleteOptions) *SingleResult

FindOneAndDelete executes a findAndModify command to delete at most one document in the collection. and returns the document as it appeared before deletion.

The filter parameter must be a document containing query operators and can be used to select the document to be deleted. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set to ErrNoDocuments 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.FindOneAndDeleteOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/findAndModify/.

Code:

var coll *mongo.Collection
var 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.M
err := 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 err == mongo.ErrNoDocuments {
        return
    }
    log.Fatal(err)
}
fmt.Printf("deleted document %v", deletedDocument)

func (*Collection) FindOneAndReplace Uses

func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{},
    replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *SingleResult

FindOneAndReplace executes a findAndModify command to replace at most one document in the collection and 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 be replaced. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set to ErrNoDocuments 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 nil and cannot contain any update operators (https://docs.mongodb.com/manual/reference/operator/update/).

The opts parameter can be used to specify options for the operation (see the options.FindOneAndReplaceOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/findAndModify/.

Code:

var coll *mongo.Collection
var 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.M
err := 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 err == mongo.ErrNoDocuments {
        return
    }
    log.Fatal(err)
}
fmt.Printf("replaced document %v", replacedDocument)

func (*Collection) FindOneAndUpdate Uses

func (coll *Collection) FindOneAndUpdate(ctx context.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 the document as it appeared before updating.

The filter parameter must be a document containing query operators and can be used to select the document to be updated. It cannot be nil. If the filter does not match any documents, a SingleResult with an error set to ErrNoDocuments 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://docs.mongodb.com/manual/reference/operator/update/) and can be used to specify the modifications to be made 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.FindOneAndUpdateOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/findAndModify/.

Code:

var coll *mongo.Collection
var 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.M
err := 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 err == mongo.ErrNoDocuments {
        return
    }
    log.Fatal(err)
}
fmt.Printf("updated document %v", updatedDocument)

func (*Collection) Indexes Uses

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 Uses

func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
    opts ...*options.InsertManyOptions) (*InsertManyResult, error)

InsertMany executes an insert command to insert multiple documents into the collection. If write errors occur during 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 must all be non-nil. For any document that does not have an _id field when transformed into BSON, one will be added automatically to the marshalled document. The original document will not be modified. The _id values for the inserted documents can be retrieved from the InsertedIDs field of the returnd InsertManyResult.

The opts parameter can be used to specify options for the operation (see the options.InsertManyOptions documentation.)

For more information about the command, see https://docs.mongodb.com/manual/reference/command/insert/.

Code:

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.Fatal(err)
}
fmt.Printf("inserted documents with IDs %v\n", res.InsertedIDs)

func (*Collection) InsertOne Uses

func (coll *Collection) InsertOne(ctx context.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 _id field when transformed into BSON, one will be added automatically to the marshalled document. The original document will 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, see https://docs.mongodb.com/manual/reference/command/insert/.

Code:

var coll *mongo.Collection

// insert the document {name: "Alice"}
res, err := coll.InsertOne(context.TODO(), bson.D{{"name", "Alice"}})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("inserted document with ID %v\n", res.InsertedID)

func (*Collection) Name Uses

func (coll *Collection) Name() string

Name returns the name of the collection.

func (*Collection) ReplaceOne Uses

func (coll *Collection) ReplaceOne(ctx context.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 be replaced. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be selected 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 nil and cannot contain any update operators (https://docs.mongodb.com/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, see https://docs.mongodb.com/manual/reference/command/update/.

Code:

var coll *mongo.Collection
var 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.Fatal(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) UpdateMany Uses

func (coll *Collection) UpdateMany(ctx context.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 be updated. It cannot be nil. If the filter 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://docs.mongodb.com/manual/reference/operator/update/) and can be used to specify the modifications to be made to 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, see https://docs.mongodb.com/manual/reference/command/update/.

Code:

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.Fatal(err)
}

if result.MatchedCount != 0 {
    fmt.Println("matched and replaced an existing document")
    return
}

func (*Collection) UpdateOne Uses

func (coll *Collection) UpdateOne(ctx context.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 be updated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from the matched set and MatchedCount will equal 1.

The update parameter must be a document containing update operators (https://docs.mongodb.com/manual/reference/operator/update/) and can be used to specify the modifications to be made 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, see https://docs.mongodb.com/manual/reference/command/update/.

Code:

var coll *mongo.Collection
var 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.Fatal(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 Uses

func (coll *Collection) Watch(ctx context.Context, pipeline interface{},
    opts ...*options.ChangeStreamOptions) (*ChangeStream, error)

Watch returns a change stream for all changes on the corresponding collection. See https://docs.mongodb.com/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 created successfully.

The pipeline parameter must be an array of documents, each representing a pipeline stage. The pipeline cannot be nil but can be empty. The stage documents must all be non-nil. See https://docs.mongodb.com/manual/changeStreams/ for a list of 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.ChangeStreamOptions documentation).

Code:

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.Fatal(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)
}

type CommandError Uses

type CommandError struct {
    Code    int32
    Message string
    Labels  []string
    Name    string
}

CommandError represents an error in execution of a command against the database.

func (CommandError) Error Uses

func (e CommandError) Error() string

Error implements the error interface.

func (CommandError) HasErrorLabel Uses

func (e CommandError) HasErrorLabel(label string) bool

HasErrorLabel returns true if the error contains the specified label.

func (CommandError) IsMaxTimeMSExpiredError Uses

func (e CommandError) IsMaxTimeMSExpiredError() bool

IsMaxTimeMSExpiredError indicates if the error is a MaxTimeMSExpiredError.

type Cursor Uses

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.
    Current bson.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 Decode method or accessed as raw BSON via the Current field.

func (*Cursor) All Uses

func (c *Cursor) All(ctx context.Context, results interface{}) error

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. This method will close the cursor after retrieving all documents. If the cursor has been iterated, any previously iterated documents will not be included in results.

This method requires driver version >= 1.1.0.

Code:

var cursor *mongo.Cursor

var results []bson.M
if err := cursor.All(context.TODO(), &results); err != nil {
    log.Fatal(err)
}
fmt.Println(results)

func (*Cursor) Close Uses

func (c *Cursor) Close(ctx context.Context) error

Close closes this cursor. Next and TryNext must not be called after Close has been called. Close is idempotent. After the first call, any subsequent calls will not change the state.

func (*Cursor) Decode Uses

func (c *Cursor) Decode(val interface{}) error

Decode will unmarshal the current document into val and return any errors from the unmarshalling process without any modification. If val is nil or is a typed nil, an error will be returned.

func (*Cursor) Err Uses

func (c *Cursor) Err() error

Err returns the last error seen by the Cursor, or nil if no error has occurred.

func (*Cursor) ID Uses

func (c *Cursor) ID() int64

ID returns the ID of this cursor, or 0 if the cursor has been closed or exhausted.

func (*Cursor) Next Uses

func (c *Cursor) Next(ctx context.Context) bool

Next gets the next document for this cursor. It returns true if there were no errors and the cursor has not been exhausted.

Next blocks until a document is available, an error occurs, or ctx expires. If ctx expires, the error will be set to ctx.Err(). In an error case, Next will return false.

If Next returns false, subsequent calls will also return false.

Code:

var cursor *mongo.Cursor
defer 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.M
    if err := cursor.Decode(&result); err != nil {
        log.Fatal(err)
    }
    fmt.Println(result)
}
if err := cursor.Err(); err != nil {
    log.Fatal(err)
}

func (*Cursor) TryNext Uses

func (c *Cursor) TryNext(ctx context.Context) bool

TryNext attempts to get the next document for this cursor. It returns true if there were no errors and the next document is available. This is only recommended for use with tailable cursors as a non-blocking alternative to Next. See https://docs.mongodb.com/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 next document 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 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 is available.

This method requires driver version >= 1.2.0.

Code:

var cursor *mongo.Cursor
defer 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.M
        if err := cursor.Decode(&result); err != nil {
            log.Fatal(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 occured. TryNext should only be called again for the empty batch case.
    if err := cursor.Err(); err != nil {
        log.Fatal(err)
    }
    if cursor.ID() == 0 {
        break
    }
}

type Database Uses

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 Uses

func (db *Database) Aggregate(ctx context.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 pipeline cannot be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, the mongo.Pipeline type can be used. See https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/#db-aggregate-stages for a list of valid stages 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, see https://docs.mongodb.com/manual/reference/command/aggregate/.

func (*Database) Client Uses

func (db *Database) Client() *Client

Client returns the Client the Database was created from.

func (*Database) Collection Uses

func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection

Collection gets a handle for a collection with the given name configured with the given CollectionOptions.

func (*Database) Drop Uses

func (db *Database) Drop(ctx context.Context) error

Drop drops the database on the server. This method ignores "namespace not found" errors so it is safe to drop a database that does not exist on the server.

func (*Database) ListCollectionNames Uses

func (db *Database) ListCollectionNames(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) ([]string, error)

ListCollectionNames executes a listCollections command and returns a slice containing the names of the collections in 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 collections are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all collections.

The opts parameter can be used to specify options for the operation (see the options.ListCollectionsOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/listCollections/.

Code:

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.Fatal(err)
}

for _, coll := range result {
    fmt.Println(coll)
}

func (*Database) ListCollections Uses

func (db *Database) ListCollections(ctx context.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 collections are included in the result. It cannot be nil. An empty document (e.g. bson.D{}) should be used to include all collections.

The opts parameter can be used to specify options for the operation (see the options.ListCollectionsOptions documentation).

For more information about the command, see https://docs.mongodb.com/manual/reference/command/listCollections/.

func (*Database) Name Uses

func (db *Database) Name() string

Name returns the name of the database.

func (*Database) ReadConcern Uses

func (db *Database) ReadConcern() *readconcern.ReadConcern

ReadConcern returns the read concern used to configure the Database object.

func (*Database) ReadPreference Uses

func (db *Database) ReadPreference() *readpref.ReadPref

ReadPreference returns the read preference used to configure the Database object.

func (*Database) RunCommand Uses

func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult

RunCommand executes the given command against the database.

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. If the command document contains a session ID or any transaction-specific fields, the behavior is undefined.

The opts parameter can be used to specify options for this operation (see the options.RunCmdOptions documentation).

Code:

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.M
if err := db.RunCommand(context.TODO(), command, opts).Decode(&result); err != nil {
    log.Fatal(err)
}
fmt.Println(result)

func (*Database) RunCommandCursor Uses

func (db *Database) RunCommandCursor(ctx context.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 command being executed does not return a cursor (e.g. insert), the command will be executed on the server and an error will be returned because the server response cannot be parsed as a cursor.

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. If the command document contains a session ID or any transaction-specific fields, the behavior is undefined.

The opts parameter can be used to specify options for this operation (see the options.RunCmdOptions documentation).

func (*Database) Watch Uses

func (db *Database) Watch(ctx context.Context, pipeline interface{},
    opts ...*options.ChangeStreamOptions) (*ChangeStream, error)

Watch returns a change stream for all changes to the corresponding database. See https://docs.mongodb.com/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 created successfully.

The pipeline parameter must be a slice of documents, each representing a pipeline stage. The pipeline cannot be nil but can be empty. The stage documents must all be non-nil. See https://docs.mongodb.com/manual/changeStreams/ for a list of 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.ChangeStreamOptions documentation).

Code:

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.Fatal(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)
}

func (*Database) WriteConcern Uses

func (db *Database) WriteConcern() *writeconcern.WriteConcern

WriteConcern returns the write concern used to configure the Database object.

type DatabaseSpecification Uses

type DatabaseSpecification struct {
    Name       string
    SizeOnDisk int64
    Empty      bool
}

DatabaseSpecification is the information for a single database returned from a ListDatabases operation.

type DeleteManyModel Uses

type DeleteManyModel struct {
    Filter    interface{}
    Collation *options.Collation
}

DeleteManyModel is the write model for deleteMany operations.

func NewDeleteManyModel Uses

func NewDeleteManyModel() *DeleteManyModel

NewDeleteManyModel creates a new DeleteManyModel.

func (*DeleteManyModel) SetCollation Uses

func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteManyModel

SetCollation sets the collation for the DeleteManyModel.

func (*DeleteManyModel) SetFilter Uses

func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel

SetFilter sets the filter for the DeleteManyModel.

type DeleteOneModel Uses

type DeleteOneModel struct {
    Filter    interface{}
    Collation *options.Collation
}

DeleteOneModel is the write model for delete operations.

func NewDeleteOneModel Uses

func NewDeleteOneModel() *DeleteOneModel

NewDeleteOneModel creates a new DeleteOneModel.

func (*DeleteOneModel) SetCollation Uses

func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOneModel

SetCollation sets the collation for the DeleteOneModel.

func (*DeleteOneModel) SetFilter Uses

func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel

SetFilter sets the filter for the DeleteOneModel.

type DeleteResult Uses

type DeleteResult struct {
    // The number of documents that were deleted.
    DeletedCount int64 `bson:"n"`
}

DeleteResult is a result of an DeleteOne operation.

type Dialer Uses

type Dialer interface {
    DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer is used to make network connections.

type EncryptionKeyVaultError Uses

type EncryptionKeyVaultError struct {
    Wrapped error
}

EncryptionKeyVaultError represents an error while communicating with the key vault collection during client side encryption.

func (EncryptionKeyVaultError) Error Uses

func (ekve EncryptionKeyVaultError) Error() string

Error implements the error interface.

type IndexModel Uses

type IndexModel struct {
    Keys    interface{}
    Options *options.IndexOptions
}

IndexModel contains information about an index.

type IndexOptionsBuilder Uses

type IndexOptionsBuilder struct {
    // contains filtered or unexported fields
}

IndexOptionsBuilder is deprecated and unused. Use mongo/options.IndexOptions instead.

func NewIndexOptionsBuilder Uses

func NewIndexOptionsBuilder() *IndexOptionsBuilder

NewIndexOptionsBuilder is deprecated.

func (*IndexOptionsBuilder) Background Uses

func (iob *IndexOptionsBuilder) Background(background bool) *IndexOptionsBuilder

Background is deprecated.

func (*IndexOptionsBuilder) Bits Uses

func (iob *IndexOptionsBuilder) Bits(bits int32) *IndexOptionsBuilder

Bits is deprecated.

func (*IndexOptionsBuilder) BucketSize Uses

func (iob *IndexOptionsBuilder) BucketSize(bucketSize int32) *IndexOptionsBuilder

BucketSize is deprecated.

func (*IndexOptionsBuilder) Build Uses

func (iob *IndexOptionsBuilder) Build() bson.D

Build is deprecated.

func (*IndexOptionsBuilder) Collation Uses

func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilder

Collation is deprecated.

func (*IndexOptionsBuilder) DefaultLanguage Uses

func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguage string) *IndexOptionsBuilder

DefaultLanguage is deprecated.

func (*IndexOptionsBuilder) ExpireAfterSeconds Uses

func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSeconds int32) *IndexOptionsBuilder

ExpireAfterSeconds is deprecated.

func (*IndexOptionsBuilder) LanguageOverride Uses

func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilder

LanguageOverride is deprecated.

func (*IndexOptionsBuilder) Max Uses

func (iob *IndexOptionsBuilder) Max(max float64) *IndexOptionsBuilder

Max is deprecated.

func (*IndexOptionsBuilder) Min Uses

func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilder

Min is deprecated.

func (*IndexOptionsBuilder) Name Uses

func (iob *IndexOptionsBuilder) Name(name string) *IndexOptionsBuilder

Name is deprecated.

func (*IndexOptionsBuilder) PartialFilterExpression Uses

func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilder

PartialFilterExpression is deprecated.

func (*IndexOptionsBuilder) Sparse Uses

func (iob *IndexOptionsBuilder) Sparse(sparse bool) *IndexOptionsBuilder

Sparse is deprecated.

func (*IndexOptionsBuilder) SphereVersion Uses

func (iob *IndexOptionsBuilder) SphereVersion(sphereVersion int32) *IndexOptionsBuilder

SphereVersion is deprecated.

func (*IndexOptionsBuilder) StorageEngine Uses

func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilder

StorageEngine is deprecated.

func (*IndexOptionsBuilder) TextVersion Uses

func (iob *IndexOptionsBuilder) TextVersion(textVersion int32) *IndexOptionsBuilder

TextVersion is deprecated.

func (*IndexOptionsBuilder) Unique Uses

func (iob *IndexOptionsBuilder) Unique(unique bool) *IndexOptionsBuilder

Unique is deprecated.

func (*IndexOptionsBuilder) Version Uses

func (iob *IndexOptionsBuilder) Version(version int32) *IndexOptionsBuilder

Version is deprecated.

func (*IndexOptionsBuilder) Weights Uses

func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilder

Weights is deprecated.

type IndexView Uses

type IndexView struct {
    // contains filtered or unexported fields
}

IndexView is used to create, drop, and list indexes on a given collection.

func (IndexView) CreateMany Uses

func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error)

CreateMany creates multiple indexes in the collection specified by the models. The names of the created indexes are returned.

func (IndexView) CreateOne Uses

func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*options.CreateIndexesOptions) (string, error)

CreateOne creates a single index in the collection specified by the model.

func (IndexView) DropAll Uses

func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOptions) (bson.Raw, error)

DropAll drops all indexes in the collection.

func (IndexView) DropOne Uses

func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.DropIndexesOptions) (bson.Raw, error)

DropOne drops the index with the given name from the collection.

func (IndexView) List Uses

func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (*Cursor, error)

List returns a cursor iterating over all the indexes in the collection.

type InsertManyResult Uses

type InsertManyResult struct {
    // Maps the indexes of inserted documents to their _id fields.
    InsertedIDs []interface{}
}

InsertManyResult is a result of an InsertMany operation.

type InsertOneModel Uses

type InsertOneModel struct {
    Document interface{}
}

InsertOneModel is the write model for insert operations.

func NewInsertOneModel Uses

func NewInsertOneModel() *InsertOneModel

NewInsertOneModel creates a new InsertOneModel.

func (*InsertOneModel) SetDocument Uses

func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel

SetDocument sets the BSON document for the InsertOneModel.

type InsertOneResult Uses

type InsertOneResult struct {
    // The identifier that was inserted.
    InsertedID interface{}
}

InsertOneResult is a result of an InsertOne operation.

InsertedID will be a Go type that corresponds to a BSON type.

type ListDatabasesResult Uses

type ListDatabasesResult struct {
    Databases []DatabaseSpecification
    TotalSize int64
}

ListDatabasesResult is a result of a ListDatabases operation. Each specification is a description of the datbases on the server.

type MarshalError Uses

type MarshalError struct {
    Value interface{}
    Err   error
}

MarshalError is returned when attempting to transform a value into a document results in an error.

func (MarshalError) Error Uses

func (me MarshalError) Error() string

Error implements the error interface.

type MongocryptError Uses

type MongocryptError struct {
    Code    int32
    Message string
}

MongocryptError is an error that occurs when executing an operation in mongocrypt.

func (MongocryptError) Error Uses

func (m MongocryptError) Error() string

Error implements the error interface.

type MongocryptdError Uses

type MongocryptdError struct {
    Wrapped error
}

MongocryptdError represents an error while communicating with mongocryptd.

func (MongocryptdError) Error Uses

func (e MongocryptdError) Error() string

Error implements the error interface.

type Pipeline Uses

type Pipeline []bson.D

Pipeline is a type that makes creating aggregation pipelines easier. It is a helper 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}}}}}},
}

type ReplaceOneModel Uses

type ReplaceOneModel struct {
    Collation   *options.Collation
    Upsert      *bool
    Filter      interface{}
    Replacement interface{}
}

ReplaceOneModel is the write model for replace operations.

func NewReplaceOneModel Uses

func NewReplaceOneModel() *ReplaceOneModel

NewReplaceOneModel creates a new ReplaceOneModel.

func (*ReplaceOneModel) SetCollation Uses

func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel

SetCollation sets the collation for the ReplaceOneModel.

func (*ReplaceOneModel) SetFilter Uses

func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel

SetFilter sets the filter for the ReplaceOneModel.

func (*ReplaceOneModel) SetReplacement Uses

func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel

SetReplacement sets the replacement document for the ReplaceOneModel.

func (*ReplaceOneModel) SetUpsert Uses

func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel

SetUpsert specifies if a new document should be created if no document matches the query.

type Session Uses

type Session interface {
    StartTransaction(...*options.TransactionOptions) error
    AbortTransaction(context.Context) error
    CommitTransaction(context.Context) error
    WithTransaction(ctx context.Context, fn func(sessCtx SessionContext) (interface{}, error),
        opts ...*options.TransactionOptions) (interface{}, error)
    ClusterTime() bson.Raw
    OperationTime() *primitive.Timestamp
    Client() *Client
    EndSession(context.Context)

    AdvanceClusterTime(bson.Raw) error
    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 consistency for a group of operations or to execute operations in an ACID transaction. A new Session can be created from a Client instance. A Session created from a Client must only be used to execute operations using that Client or a Database or Collection created from that Client. Custom implementations of this interface should not be used in production. For more information about sessions, and their use cases, see https://docs.mongodb.com/manual/reference/server-sessions/, https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#causal-consistency, and https://docs.mongodb.com/manual/core/transactions/.

StartTransaction starts a new transaction, configured with the given options, on this session. This method will return an error if there is already a transaction in-progress for this session.

CommitTransaction commits the active transaction for this session. This method will return an error if there is no active transaction for this session or the transaction has been aborted.

AbortTransaction aborts the active transaction for this session. This method will return an error if there is no active transaction for this session or the transaction has been committed or aborted.

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, sessCtx 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. For a usage example, see the Client.StartSession method documentation.

ClusterTime, OperationTime, and Client return the session's current operation time, the session's current cluster time, and the Client associated with the session, respectively.

EndSession method should abort any existing transactions and close the session.

AdvanceClusterTime and AdvanceOperationTime are for internal use only and must not be called.

type SessionContext Uses

type SessionContext interface {
    context.Context
    Session
}

SessionContext combines the context.Context and mongo.Session interfaces. It should be used as the Context arguments to operations that should be executed in a session. This type is not goroutine safe and must not be used concurrently by multiple goroutines.

type SingleResult Uses

type SingleResult struct {
    // contains filtered or unexported fields
}

SingleResult represents a single document returned from an operation. If the operation returned an error, the Err method of SingleResult will return that error.

func (*SingleResult) Decode Uses

func (sr *SingleResult) Decode(v interface{}) error

Decode will attempt to decode the first document into v. If there was an error from the operation that created this SingleResult then the error will be returned. If there were no returned documents, ErrNoDocuments is returned. If v is nil or is a typed nil, an error will be returned.

func (*SingleResult) DecodeBytes Uses

func (sr *SingleResult) DecodeBytes() (bson.Raw, error)

DecodeBytes will return a copy of the document as a bson.Raw. If there was an error from the operation that created this SingleResult then the error will be returned along with the result. If there were no returned documents, ErrNoDocuments is returned.

func (*SingleResult) Err Uses

func (sr *SingleResult) Err() error

Err will return the error from the operation that created this SingleResult. If there was no error, nil is returned.

type StreamType Uses

type StreamType uint8

StreamType represents the cluster type against which a ChangeStream was created.

const (
    CollectionStream StreamType = iota
    DatabaseStream
    ClientStream
)

These constants represent valid change stream types. A change stream can be initialized over a collection, all collections in a database, or over a cluster.

type UpdateManyModel Uses

type UpdateManyModel struct {
    Collation    *options.Collation
    Upsert       *bool
    Filter       interface{}
    Update       interface{}
    ArrayFilters *options.ArrayFilters
}

UpdateManyModel is the write model for updateMany operations.

func NewUpdateManyModel Uses

func NewUpdateManyModel() *UpdateManyModel

NewUpdateManyModel creates a new UpdateManyModel.

func (*UpdateManyModel) SetArrayFilters Uses

func (umm *UpdateManyModel) SetArrayFilters(filters options.ArrayFilters) *UpdateManyModel

SetArrayFilters specifies a set of filters specifying to which array elements an update should apply.

func (*UpdateManyModel) SetCollation Uses

func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel

SetCollation sets the collation for the UpdateManyModel.

func (*UpdateManyModel) SetFilter Uses

func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel

SetFilter sets the filter for the UpdateManyModel.

func (*UpdateManyModel) SetUpdate Uses

func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel

SetUpdate sets the update document for the UpdateManyModel.

func (*UpdateManyModel) SetUpsert Uses

func (umm *UpdateManyModel) SetUpsert(upsert bool) *UpdateManyModel

SetUpsert specifies if a new document should be created if no document matches the query.

type UpdateOneModel Uses

type UpdateOneModel struct {
    Collation    *options.Collation
    Upsert       *bool
    Filter       interface{}
    Update       interface{}
    ArrayFilters *options.ArrayFilters
}

UpdateOneModel is the write model for update operations.

func NewUpdateOneModel Uses

func NewUpdateOneModel() *UpdateOneModel

NewUpdateOneModel creates a new UpdateOneModel.

func (*UpdateOneModel) SetArrayFilters Uses

func (uom *UpdateOneModel) SetArrayFilters(filters options.ArrayFilters) *UpdateOneModel

SetArrayFilters specifies a set of filters specifying to which array elements an update should apply.

func (*UpdateOneModel) SetCollation Uses

func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel

SetCollation sets the collation for the UpdateOneModel.

func (*UpdateOneModel) SetFilter Uses

func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel

SetFilter sets the filter for the UpdateOneModel.

func (*UpdateOneModel) SetUpdate Uses

func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel

SetUpdate sets the update document for the UpdateOneModel.

func (*UpdateOneModel) SetUpsert Uses

func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel

SetUpsert specifies if a new document should be created if no document matches the query.

type UpdateResult Uses

type UpdateResult struct {
    // The number of documents that matched the filter.
    MatchedCount int64
    // The number of documents that were modified.
    ModifiedCount int64
    // The number of documents that were upserted.
    UpsertedCount int64
    // The identifier of the inserted document if an upsert took place.
    UpsertedID interface{}
}

UpdateResult is a result of an update operation.

UpsertedID will be a Go type that corresponds to a BSON type.

func (*UpdateResult) UnmarshalBSON Uses

func (result *UpdateResult) UnmarshalBSON(b []byte) error

UnmarshalBSON implements the bson.Unmarshaler interface.

type WriteConcernError Uses

type WriteConcernError struct {
    Name    string
    Code    int
    Message string
    Details bson.Raw
}

WriteConcernError is a write concern failure that occurred as a result of a write operation.

func (WriteConcernError) Error Uses

func (wce WriteConcernError) Error() string

type WriteError Uses

type WriteError struct {
    Index   int
    Code    int
    Message string
}

WriteError is a non-write concern failure that occurred as a result of a write operation.

func (WriteError) Error Uses

func (we WriteError) Error() string

type WriteErrors Uses

type WriteErrors []WriteError

WriteErrors is a group of non-write concern failures that occurred as a result of a write operation.

func (WriteErrors) Error Uses

func (we WriteErrors) Error() string

type WriteException Uses

type WriteException struct {
    WriteConcernError *WriteConcernError
    WriteErrors       WriteErrors
}

WriteException is an error for a non-bulk write operation.

func (WriteException) Error Uses

func (mwe WriteException) Error() string

type WriteModel Uses

type WriteModel interface {
    // contains filtered or unexported methods
}

WriteModel is the interface satisfied by all models for bulk writes.

type XSession Uses

type XSession interface {
    ClientSession() *session.Client
    ID() bsonx.Doc
}

XSession is an unstable interface for internal use only. This interface is deprecated and is not part of the stability guarantee. It may be removed at any time.

Directories

PathSynopsis
gridfs
options
readconcern
readpref
writeconcern

Package mongo imports 34 packages (graph) and is imported by 298 packages. Updated 2019-11-22. Refresh now. Tools for package owners.