Documentation ¶
Overview ¶
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 Connect:
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://foo:bar@localhost:27017")) if err != nil { return err }
This will create a new client and start monitoring the MongoDB server on localhost. The Database and Collection types can be used to access the database:
collection := client.Database("baz").Collection("qux")
A Collection can be used to query the database or insert documents:
res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"}) if err != nil { return err } id := res.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 }
Cursor.All will decode all of the returned elements at once:
var results []struct{ Foo string Bar int32 } if err = cur.All(context.Background(), &results); err != nil { log.Fatal(err) } // do something with results...
Methods that only return a single document will return a *SingleResult, which 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.
Error Handling ¶
Errors from the MongoDB server will implement the ServerError interface, which has functions to check for specific error codes, labels, and message substrings. These can be used to check for and handle specific errors. Some methods, like InsertMany and BulkWrite, can return an error representing multiple errors, and in those cases the ServerError functions will return true if any of the contained errors satisfy the check.
There are also helper functions to check for certain specific types of errors:
IsDuplicateKeyError(error) IsNetworkError(error) IsTimeout(error)
Potential DNS Issues ¶
Building with Go 1.11+ and using connection strings with the "mongodb+srv"[1] scheme is 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. libmongocrypt version 1.3.0 or higher is required when using driver version 1.8.0 or higher. 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.
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
Example (ClientSideEncryption) ¶
Output:
Example (ClientSideEncryptionCreateKey) ¶
Output:
Example (ExplictEncryption) ¶
Output:
Example (ExplictEncryptionWithAutomaticDecryption) ¶
Output:
Index ¶
- Variables
- func BatchCursorFromCursor(c *Cursor) *driver.BatchCursordeprecated
- func IsDuplicateKeyError(err error) bool
- func IsNetworkError(err error) bool
- func IsTimeout(err error) bool
- func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error
- type BSONAppender
- type BSONAppenderFunc
- type BulkWriteError
- type BulkWriteException
- func (bwe BulkWriteException) Error() string
- func (bwe BulkWriteException) HasErrorCode(code int) bool
- func (bwe BulkWriteException) HasErrorCodeWithMessage(code int, message string) bool
- func (bwe BulkWriteException) HasErrorLabel(label string) bool
- func (bwe BulkWriteException) HasErrorMessage(message string) bool
- type BulkWriteResult
- type ChangeStream
- func (cs *ChangeStream) Close(ctx context.Context) error
- func (cs *ChangeStream) Decode(val interface{}) error
- func (cs *ChangeStream) Err() error
- func (cs *ChangeStream) ID() int64
- func (cs *ChangeStream) Next(ctx context.Context) bool
- func (cs *ChangeStream) ResumeToken() bson.Raw
- func (cs *ChangeStream) TryNext(ctx context.Context) bool
- type Client
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database
- func (c *Client) Disconnect(ctx context.Context) error
- func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error)
- func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult, error)
- func (c *Client) NumberSessionsInProgress() int
- func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error
- func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)
- func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error
- func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, ...) error
- func (c *Client) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- type ClientEncryption
- func (ce *ClientEncryption) Close(ctx context.Context) error
- func (ce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider string, opts ...*options.DataKeyOptions) (primitive.Binary, error)
- func (ce *ClientEncryption) Decrypt(ctx context.Context, val primitive.Binary) (bson.RawValue, error)
- func (ce *ClientEncryption) Encrypt(ctx context.Context, val bson.RawValue, opts ...*options.EncryptOptions) (primitive.Binary, error)
- type Collection
- func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Cursor, error)
- func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, opts ...*options.BulkWriteOptions) (*BulkWriteResult, error)
- func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection, error)
- func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)
- func (coll *Collection) Database() *Database
- func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error)
- func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error)
- func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, ...) ([]interface{}, error)
- func (coll *Collection) Drop(ctx context.Context) error
- func (coll *Collection) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error)
- func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (cur *Cursor, err error)
- func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *SingleResult
- func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, ...) *SingleResult
- func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, ...) *SingleResult
- func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, ...) *SingleResult
- func (coll *Collection) Indexes() IndexView
- func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, ...) (*InsertManyResult, error)
- func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*InsertOneResult, error)
- func (coll *Collection) Name() string
- func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) UpdateByID(ctx context.Context, id interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, ...) (*UpdateResult, error)
- func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- type CollectionSpecification
- type CommandError
- func (e CommandError) Error() string
- func (e CommandError) HasErrorCode(code int) bool
- func (e CommandError) HasErrorCodeWithMessage(code int, message string) bool
- func (e CommandError) HasErrorLabel(label string) bool
- func (e CommandError) HasErrorMessage(message string) bool
- func (e CommandError) IsMaxTimeMSExpiredError() bool
- func (e CommandError) Unwrap() error
- type Cursor
- func (c *Cursor) All(ctx context.Context, results interface{}) error
- func (c *Cursor) Close(ctx context.Context) error
- func (c *Cursor) Decode(val interface{}) error
- func (c *Cursor) Err() error
- func (c *Cursor) ID() int64
- func (c *Cursor) Next(ctx context.Context) bool
- func (c *Cursor) RemainingBatchLength() int
- func (c *Cursor) TryNext(ctx context.Context) bool
- type Database
- func (db *Database) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Cursor, error)
- func (db *Database) Client() *Client
- func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection
- func (db *Database) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error
- func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{}, ...) error
- func (db *Database) Drop(ctx context.Context) error
- func (db *Database) ListCollectionNames(ctx context.Context, filter interface{}, ...) ([]string, error)
- func (db *Database) ListCollectionSpecifications(ctx context.Context, filter interface{}, ...) ([]*CollectionSpecification, error)
- func (db *Database) ListCollections(ctx context.Context, filter interface{}, ...) (*Cursor, error)
- func (db *Database) Name() string
- func (db *Database) ReadConcern() *readconcern.ReadConcern
- func (db *Database) ReadPreference() *readpref.ReadPref
- func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
- func (db *Database) RunCommandCursor(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor, error)
- func (db *Database) Watch(ctx context.Context, pipeline interface{}, ...) (*ChangeStream, error)
- func (db *Database) WriteConcern() *writeconcern.WriteConcern
- type DatabaseSpecification
- type DeleteManyModel
- type DeleteOneModel
- type DeleteResult
- type Dialer
- type EncryptionKeyVaultError
- type ErrMapForOrderedArgument
- type IndexModel
- type IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Background(background bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Bits(bits int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) BucketSize(bucketSize int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Build() bson.Ddeprecated
- func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguage string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSeconds int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Max(max float64) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Name(name string) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Sparse(sparse bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) SphereVersion(sphereVersion int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) TextVersion(textVersion int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Unique(unique bool) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Version(version int32) *IndexOptionsBuilderdeprecated
- func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilderdeprecated
- type IndexSpecification
- type IndexView
- func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, ...) ([]string, error)
- func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*options.CreateIndexesOptions) (string, error)
- func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOptions) (bson.Raw, error)
- func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.DropIndexesOptions) (bson.Raw, error)
- func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (*Cursor, error)
- func (iv IndexView) ListSpecifications(ctx context.Context, opts ...*options.ListIndexesOptions) ([]*IndexSpecification, error)
- type InsertManyResult
- type InsertOneModel
- type InsertOneResult
- type ListDatabasesResult
- type MarshalError
- type MongocryptError
- type MongocryptdError
- type Pipeline
- type ReplaceOneModel
- func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel
- func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel
- type ServerError
- type Session
- type SessionContext
- type SingleResult
- type StreamType
- type UpdateManyModel
- func (umm *UpdateManyModel) SetArrayFilters(filters options.ArrayFilters) *UpdateManyModel
- func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel
- func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel
- func (umm *UpdateManyModel) SetUpsert(upsert bool) *UpdateManyModel
- type UpdateOneModel
- func (uom *UpdateOneModel) SetArrayFilters(filters options.ArrayFilters) *UpdateOneModel
- func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel
- func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel
- func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel
- type UpdateResult
- type WriteConcernError
- type WriteError
- type WriteErrors
- type WriteException
- type WriteModel
- type XSessiondeprecated
- Bugs
Examples ¶
- Package (ClientSideEncryption)
- Package (ClientSideEncryptionCreateKey)
- Package (ExplictEncryption)
- Package (ExplictEncryptionWithAutomaticDecryption)
- ChangeStream.Next
- ChangeStream.ResumeToken
- ChangeStream.TryNext
- Client
- Client.ListDatabaseNames
- Client.StartSession (WithTransaction)
- Client.UseSessionWithOptions
- Client.Watch
- Collection.Aggregate
- Collection.BulkWrite
- Collection.CountDocuments
- Collection.DeleteMany
- Collection.DeleteOne
- Collection.Distinct
- Collection.EstimatedDocumentCount
- Collection.Find
- Collection.FindOne
- Collection.FindOneAndDelete
- Collection.FindOneAndReplace
- Collection.FindOneAndUpdate
- Collection.InsertMany
- Collection.InsertOne
- Collection.ReplaceOne
- Collection.UpdateMany
- Collection.UpdateOne
- Collection.Watch
- Connect (AWS)
- Connect (Direct)
- Connect (Kerberos)
- Connect (PLAIN)
- Connect (Ping)
- Connect (ReplicaSet)
- Connect (SCRAM)
- Connect (SRV)
- Connect (Sharded)
- Connect (StableAPI)
- Connect (X509)
- Cursor.All
- Cursor.Next
- Cursor.RemainingBatchLength
- Cursor.TryNext
- Database.CreateCollection
- Database.CreateView
- Database.ListCollectionNames
- Database.RunCommand
- Database.Watch
- IndexView.CreateMany
- IndexView.List
- NewSessionContext
- WithSession
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMissingResumeToken indicates that a change stream notification from the server did not contain a resume token. ErrMissingResumeToken = errors.New("cannot provide resume functionality when the resume token is missing") // ErrNilCursor indicates that the underlying cursor for the change stream is nil. ErrNilCursor = errors.New("cursor is nil") )
var ErrClientDisconnected = errors.New("client is disconnected")
ErrClientDisconnected is returned when disconnected Client is used to run an operation.
var ErrEmptySlice = errors.New("must provide at least one element in input slice")
ErrEmptySlice is returned when an empty slice is passed to a CRUD method that requires a non-empty slice.
var ErrInvalidIndexValue = errors.New("invalid index value")
ErrInvalidIndexValue is returned if an index is created with a keys document that has a value that is not a number or string.
var ErrMultipleIndexDrop = errors.New("multiple indexes would be dropped")
ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne.
var ErrNilDocument = errors.New("document is nil")
ErrNilDocument is returned when a nil document is passed to a CRUD method.
var ErrNilValue = errors.New("value is nil")
ErrNilValue is returned when a nil value is passed to a CRUD method.
var ErrNoDocuments = errors.New("mongo: no documents in result")
ErrNoDocuments is returned by SingleResult methods when the operation that created the SingleResult did not return any documents.
var ErrNonStringIndexName = errors.New("index name must be a string")
ErrNonStringIndexName is returned if an index is created with a name that is not a string.
var ErrUnacknowledgedWrite = errors.New("unacknowledged write")
ErrUnacknowledgedWrite is returned by operations that have an unacknowledged write concern.
var ErrWrongClient = errors.New("session was not created by this client")
ErrWrongClient is returned when a user attempts to pass in a session created by a different client than the method call is using.
Functions ¶
func BatchCursorFromCursor
deprecated
added in
v1.1.0
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.
Deprecated: This is an unstable function because the driver.BatchCursor type exists in the "x" package. Neither this function nor the driver.BatchCursor type should be used by applications and may be changed or removed in any release.
func IsDuplicateKeyError ¶ added in v1.5.0
IsDuplicateKeyError returns true if err is a duplicate key error
func IsNetworkError ¶ added in v1.5.0
IsNetworkError returns true if err is a network error
func WithSession ¶ added in v0.0.16
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.
Types ¶
type BSONAppender ¶ added in v0.0.15
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 ¶ added in v0.0.15
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 ¶ added in v0.0.15
func (baf BSONAppenderFunc) AppendBSON(dst []byte, val interface{}) ([]byte, error)
AppendBSON implements the BSONAppender interface
type BulkWriteError ¶ added in v0.0.4
type BulkWriteError struct { WriteError // The WriteError that occurred. Request WriteModel // The WriteModel that caused this error. }
BulkWriteError is an error that occurred during execution of one operation in a BulkWrite. This error type is only returned as part of a BulkWriteException.
func (BulkWriteError) Error ¶ added in v0.0.4
func (bwe BulkWriteError) Error() string
Error implements the error interface.
type BulkWriteException ¶ added in v0.0.16
type BulkWriteException struct { // The write concern error that occurred, or nil if there was none. WriteConcernError *WriteConcernError // The write errors that occurred during operation execution. WriteErrors []BulkWriteError // The categories to which the exception belongs. Labels []string }
BulkWriteException is the error type returned by BulkWrite and InsertMany operations.
func (BulkWriteException) Error ¶ added in v0.0.16
func (bwe BulkWriteException) Error() string
Error implements the error interface.
func (BulkWriteException) HasErrorCode ¶ added in v1.5.0
func (bwe BulkWriteException) HasErrorCode(code int) bool
HasErrorCode returns true if any of the errors have the specified code.
func (BulkWriteException) HasErrorCodeWithMessage ¶ added in v1.5.0
func (bwe BulkWriteException) HasErrorCodeWithMessage(code int, message string) bool
HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message.
func (BulkWriteException) HasErrorLabel ¶ added in v1.4.0
func (bwe BulkWriteException) HasErrorLabel(label string) bool
HasErrorLabel returns true if the error contains the specified label.
func (BulkWriteException) HasErrorMessage ¶ added in v1.5.0
func (bwe BulkWriteException) HasErrorMessage(message string) bool
HasErrorMessage returns true if the error contains the specified message.
type BulkWriteResult ¶ added in v0.0.16
type BulkWriteResult struct { // The number of documents inserted. InsertedCount int64 // The number of documents matched by filters in update and replace operations. MatchedCount int64 // The number of documents modified by update and replace operations. ModifiedCount int64 // The number of documents deleted. DeletedCount int64 // The number of documents upserted by update and replace operations. UpsertedCount int64 // A map of operation index to the _id of each upserted document. UpsertedIDs map[int64]interface{} }
BulkWriteResult is the result type returned by a BulkWrite operation.
type ChangeStream ¶ added in v0.3.0
type ChangeStream struct { // Current is the BSON bytes of the current event. This property is only valid until the next call to Next or // TryNext. If continued access is required, a copy must be made. 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. This type is not goroutine safe and must not be used concurrently by multiple goroutines. For more information about change streams, see https://docs.mongodb.com/manual/changeStreams/.
func (*ChangeStream) Close ¶ added in v0.3.0
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 ¶ added in v0.3.0
func (cs *ChangeStream) Decode(val interface{}) error
Decode will unmarshal the current event document into val and return any errors from the unmarshalling process without any modification. If val is nil or is a typed nil, an error will be returned.
func (*ChangeStream) Err ¶ added in v0.3.0
func (cs *ChangeStream) Err() error
Err returns the last error seen by the change stream, or nil if no errors has occurred.
func (*ChangeStream) ID ¶ added in v0.3.0
func (cs *ChangeStream) ID() int64
ID returns the ID for this change stream, or 0 if the cursor has been closed or exhausted.
func (*ChangeStream) Next ¶ added in v0.3.0
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.
func (*ChangeStream) ResumeToken ¶ added in v1.1.0
func (cs *ChangeStream) ResumeToken() bson.Raw
ResumeToken returns the last cached resume token for this change stream, or nil if a resume token has not been stored.
func (*ChangeStream) TryNext ¶ added in v1.2.0
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.
type Client ¶
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.
func Connect ¶ added in v0.0.3
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.
func NewClient ¶
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 ¶ added in v0.0.3
Connect initializes the Client by starting background monitoring goroutines. If the Client was created using the NewClient function, this method must be called before a Client can be used.
Connect starts background goroutines to monitor the state of the deployment and does not do any I/O in the main goroutine. The Client.Ping method can be used to verify that the connection was created successfully.
func (*Client) Database ¶
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 ¶ added in v0.0.3
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 ¶ added in v0.0.3
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/.
func (*Client) ListDatabases ¶ added in v0.0.3
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 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/.
func (*Client) NumberSessionsInProgress ¶ added in v1.2.0
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 ¶ added in v0.0.14
Ping sends a ping command to verify that the client can connect to the deployment.
The rp parameter is used to determine which server is selected for the operation. If it is nil, the client's read preference is used.
If the server is down, Ping will try to select a server until the client's server selection timeout expires. This can be configured through the ClientOptions.SetServerSelectionTimeout option when creating a new Client. After the timeout expires, a server selection error is returned.
Using Ping reduces application resilience because applications starting up will error if the server is temporarily unavailable or is failing over (e.g. during autoscaling due to a load spike).
func (*Client) StartSession ¶ added in v0.0.10
func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)
StartSession starts a new session configured with the given options.
StartSession does not actually communicate with the server and will not error if the client is disconnected.
If the DefaultReadConcern, DefaultWriteConcern, or DefaultReadPreference options are not set, the client's read concern, write concern, or read preference will be used, respectively.
func (*Client) UseSession ¶ added in v0.0.16
UseSession creates a new Session and uses it to create a new SessionContext, which is used to call the fn callback. The SessionContext parameter must be used as the Context parameter for any operations in the fn callback that 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 ¶ added in v0.0.16
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.
func (*Client) Watch ¶ added in v0.1.0
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).
type ClientEncryption ¶ added in v1.2.0
type ClientEncryption struct {
// contains filtered or unexported fields
}
ClientEncryption is used to create data keys and explicitly encrypt and decrypt BSON values.
func NewClientEncryption ¶ added in v1.2.0
func NewClientEncryption(keyVaultClient *Client, opts ...*options.ClientEncryptionOptions) (*ClientEncryption, error)
NewClientEncryption creates a new ClientEncryption instance configured with the given options.
func (*ClientEncryption) Close ¶ added in v1.2.0
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 ¶ added in v1.2.0
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 ¶ added in v1.2.0
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 ¶ added in v1.2.0
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 ¶
type Collection struct {
// contains filtered or unexported fields
}
Collection is a handle to a MongoDB collection. It is safe for concurrent use by multiple goroutines.
func (*Collection) Aggregate ¶
func (coll *Collection) Aggregate(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/.
func (*Collection) BulkWrite ¶ added in v0.0.16
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.)
func (*Collection) Clone ¶ added in v0.0.9
func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection, error)
Clone creates a copy of the Collection configured with the given CollectionOptions. The specified options are merged with the existing options on the collection, with the specified options taking precedence.
func (*Collection) CountDocuments ¶ added in v0.0.11
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).
func (*Collection) Database ¶ added in v0.0.15
func (coll *Collection) Database() *Database
Database returns the Database that was used to create the Collection.
func (*Collection) DeleteMany ¶
func (coll *Collection) DeleteMany(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 operators 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/.
func (*Collection) DeleteOne ¶
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 operators 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/.
func (*Collection) Distinct ¶
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/.
func (*Collection) Drop ¶ added in v0.0.4
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 ¶ added in v0.0.11
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/.
func (*Collection) Find ¶
func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (cur *Cursor, err 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/.
func (*Collection) FindOne ¶
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/.
func (*Collection) FindOneAndDelete ¶
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/.
func (*Collection) FindOneAndReplace ¶
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/.
func (*Collection) FindOneAndUpdate ¶
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/.
func (*Collection) Indexes ¶ added in v0.0.3
func (coll *Collection) Indexes() IndexView
Indexes returns an IndexView instance that can be used to perform operations on the indexes for the collection.
func (*Collection) InsertMany ¶
func (coll *Collection) InsertMany(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 returned InsertManyResult.
The opts parameter can be used to specify options for the operation (see the options.InsertManyOptions documentation.)
For more information about the command, see https://docs.mongodb.com/manual/reference/command/insert/.
func (*Collection) InsertOne ¶
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/.
func (*Collection) Name ¶ added in v0.0.4
func (coll *Collection) Name() string
Name returns the name of the collection.
func (*Collection) ReplaceOne ¶
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/.
func (*Collection) UpdateByID ¶ added in v1.5.0
func (coll *Collection) UpdateByID(ctx context.Context, id interface{}, update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error)
UpdateByID executes an update command to update the document whose _id value matches the provided ID in the collection. This is equivalent to running UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...).
The id parameter is the _id of the document to be updated. It cannot be nil. If the ID does not match any documents, the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned.
The update parameter must be a document containing update operators (https://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/.
func (*Collection) UpdateMany ¶
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/.
func (*Collection) UpdateOne ¶
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/.
func (*Collection) Watch ¶ added in v0.0.2
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).
type CollectionSpecification ¶ added in v1.5.0
type CollectionSpecification struct { // The collection name. Name string // The type of the collection. This will either be "collection" or "view". Type string // Whether or not the collection is readOnly. This will be false for MongoDB versions < 3.4. ReadOnly bool // The collection UUID. This field will be nil for MongoDB versions < 3.6. For versions 3.6 and higher, this will // be a primitive.Binary with Subtype 4. UUID *primitive.Binary // A document containing the options used to construct the collection. Options bson.Raw // An IndexSpecification instance with details about the collection's _id index. This will be nil if the NameOnly // option is used and for MongoDB versions < 3.4. IDIndex *IndexSpecification }
CollectionSpecification represents a collection in a database. This type is returned by the Database.ListCollectionSpecifications function.
func (*CollectionSpecification) UnmarshalBSON ¶ added in v1.5.0
func (cs *CollectionSpecification) UnmarshalBSON(data []byte) error
UnmarshalBSON implements the bson.Unmarshaler interface.
type CommandError ¶ added in v1.0.0
type CommandError struct { Code int32 Message string Labels []string // Categories to which the error belongs Name string // A human-readable name corresponding to the error code Wrapped error // The underlying error, if one exists. Raw bson.Raw // The original server response containing the error. }
CommandError represents a server error during execution of a command. This can be returned by any operation.
func (CommandError) Error ¶ added in v1.0.0
func (e CommandError) Error() string
Error implements the error interface.
func (CommandError) HasErrorCode ¶ added in v1.5.0
func (e CommandError) HasErrorCode(code int) bool
HasErrorCode returns true if the error has the specified code.
func (CommandError) HasErrorCodeWithMessage ¶ added in v1.5.0
func (e CommandError) HasErrorCodeWithMessage(code int, message string) bool
HasErrorCodeWithMessage returns true if the error has the specified code and Message contains the specified message.
func (CommandError) HasErrorLabel ¶ added in v1.0.0
func (e CommandError) HasErrorLabel(label string) bool
HasErrorLabel returns true if the error contains the specified label.
func (CommandError) HasErrorMessage ¶ added in v1.5.0
func (e CommandError) HasErrorMessage(message string) bool
HasErrorMessage returns true if the error contains the specified message.
func (CommandError) IsMaxTimeMSExpiredError ¶ added in v1.1.0
func (e CommandError) IsMaxTimeMSExpiredError() bool
IsMaxTimeMSExpiredError returns true if the error is a MaxTimeMSExpired error.
func (CommandError) Unwrap ¶ added in v1.4.0
func (e CommandError) Unwrap() error
Unwrap returns the underlying error.
type Cursor ¶
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. This type is not goroutine safe and must not be used concurrently by multiple goroutines.
func NewCursorFromDocuments ¶ added in v1.9.0
func NewCursorFromDocuments(documents []interface{}, err error, registry *bsoncodec.Registry) (*Cursor, error)
NewCursorFromDocuments creates a new Cursor pre-loaded with the provided documents, error and registry. If no registry is provided, bson.DefaultRegistry will be used.
The documents parameter must be a slice of documents. The slice may be nil or empty, but all elements must be non-nil.
func (*Cursor) All ¶ added in v1.1.0
All iterates the cursor and decodes each document into results. The results parameter must be a pointer to a slice. The slice pointed to by results will be completely overwritten. 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.
func (*Cursor) Close ¶ added in v0.0.2
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 ¶ added in v0.0.2
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 ¶ added in v0.0.2
Err returns the last error seen by the Cursor, or nil if no error has occurred.
func (*Cursor) ID ¶ added in v0.0.2
ID returns the ID of this cursor, or 0 if the cursor has been closed or exhausted.
func (*Cursor) Next ¶ added in v0.0.2
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.
func (*Cursor) RemainingBatchLength ¶ added in v1.4.0
RemainingBatchLength returns the number of documents left in the current batch. If this returns zero, the subsequent call to Next or TryNext will do a network request to fetch the next batch.
func (*Cursor) TryNext ¶ added in v1.2.0
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.
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database is a handle to a MongoDB database. It is safe for concurrent use by multiple goroutines.
func (*Database) Aggregate ¶ added in v1.1.0
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) Collection ¶
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) CreateCollection ¶ added in v1.4.0
func (db *Database) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error
CreateCollection executes a create command to explicitly create a new collection with the specified name on the server. If the collection being created already exists, this method will return a mongo.CommandError. This method requires driver version 1.4.0 or higher.
The opts parameter can be used to specify options for the operation (see the options.CreateCollectionOptions documentation).
For more information about the command, see https://docs.mongodb.com/manual/reference/command/create/.
func (*Database) CreateView ¶ added in v1.4.0
func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{}, opts ...*options.CreateViewOptions) error
CreateView executes a create command to explicitly create a view on the server. See https://docs.mongodb.com/manual/core/views/ for more information about views. This method requires driver version >= 1.4.0 and MongoDB version >= 3.4.
The viewName parameter specifies the name of the view to create.
The viewOn parameter specifies the name of the collection or view on which this view will be created ¶
The pipeline parameter specifies an aggregation pipeline that will be exececuted against the source collection or view to create this view.
The opts parameter can be used to specify options for the operation (see the options.CreateViewOptions documentation).
func (*Database) Drop ¶ added in v0.0.4
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 ¶ added in v1.1.0
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/.
BUG(benjirewis): ListCollectionNames prevents listing more than 100 collections per database when running against MongoDB version 2.6.
func (*Database) ListCollectionSpecifications ¶ added in v1.5.0
func (db *Database) ListCollectionSpecifications(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) ([]*CollectionSpecification, error)
ListCollectionSpecifications executes a listCollections command and returns a slice of CollectionSpecification instances representing 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/.
BUG(benjirewis): ListCollectionSpecifications prevents listing more than 100 collections per database when running against MongoDB version 2.6.
func (*Database) ListCollections ¶ added in v0.0.6
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/.
BUG(benjirewis): ListCollections prevents listing more than 100 collections per database when running against MongoDB version 2.6.
func (*Database) ReadConcern ¶ added in v0.0.13
func (db *Database) ReadConcern() *readconcern.ReadConcern
ReadConcern returns the read concern used to configure the Database object.
func (*Database) ReadPreference ¶ added in v0.0.13
ReadPreference returns the read preference used to configure the Database object.
func (*Database) RunCommand ¶
func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult
RunCommand executes the given command against the database. This function does not obey the Database's read preference. To specify a read preference, the RunCmdOptions.ReadPreference option must be used.
The runCommand parameter must be a document for the command to be executed. It cannot be nil. This must be an order-preserving type such as bson.D. Map types such as bson.M are not valid. If the command document contains a session ID or any transaction-specific fields, the behavior is undefined. Specifying API versioning options in the command document and declaring an API version on the client is not supported. The behavior of RunCommand is undefined in this case.
The opts parameter can be used to specify options for this operation (see the options.RunCmdOptions documentation).
func (*Database) RunCommandCursor ¶ added in v0.1.0
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. This function does not obey the Database's read preference. To specify a read preference, the RunCmdOptions.ReadPreference option must be used.
The runCommand parameter must be a document for the command to be executed. It cannot be nil. This must be an order-preserving type such as bson.D. Map types such as bson.M are not valid. 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 ¶ added in v0.1.0
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).
func (*Database) WriteConcern ¶ added in v0.0.13
func (db *Database) WriteConcern() *writeconcern.WriteConcern
WriteConcern returns the write concern used to configure the Database object.
type DatabaseSpecification ¶ added in v0.0.3
type DatabaseSpecification struct { Name string // The name of the database. SizeOnDisk int64 // The total size of the database files on disk in bytes. Empty bool // Specfies whether or not the database is empty. }
DatabaseSpecification contains information for a database. This type is returned as part of ListDatabasesResult.
type DeleteManyModel ¶ added in v0.0.16
DeleteManyModel is used to delete multiple documents in a BulkWrite operation.
func NewDeleteManyModel ¶ added in v0.0.16
func NewDeleteManyModel() *DeleteManyModel
NewDeleteManyModel creates a new DeleteManyModel.
func (*DeleteManyModel) SetCollation ¶ added in v0.3.0
func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteManyModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will be used.
func (*DeleteManyModel) SetFilter ¶ added in v0.3.0
func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel
SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing query operators. It cannot be nil.
func (*DeleteManyModel) SetHint ¶ added in v1.4.0
func (dmm *DeleteManyModel) SetHint(hint interface{}) *DeleteManyModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the index specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option is specified. The driver will return an error if this option is specified during an unacknowledged write operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
type DeleteOneModel ¶ added in v0.0.16
DeleteOneModel is used to delete at most one document in a BulkWriteOperation.
func NewDeleteOneModel ¶ added in v0.0.16
func NewDeleteOneModel() *DeleteOneModel
NewDeleteOneModel creates a new DeleteOneModel.
func (*DeleteOneModel) SetCollation ¶ added in v0.3.0
func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will be used.
func (*DeleteOneModel) SetFilter ¶ added in v0.3.0
func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel
SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing query operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching documents.
func (*DeleteOneModel) SetHint ¶ added in v1.4.0
func (dom *DeleteOneModel) SetHint(hint interface{}) *DeleteOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the index specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option is specified. The driver will return an error if this option is specified during an unacknowledged write operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
type DeleteResult ¶
type DeleteResult struct {
DeletedCount int64 `bson:"n"` // The number of documents deleted.
}
DeleteResult is the result type returned by DeleteOne and DeleteMany operations.
type Dialer ¶ added in v0.0.3
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
Dialer is used to make network connections.
type EncryptionKeyVaultError ¶ added in v1.2.0
type EncryptionKeyVaultError struct {
Wrapped error
}
EncryptionKeyVaultError represents an error while communicating with the key vault collection during client-side encryption.
func (EncryptionKeyVaultError) Error ¶ added in v1.2.0
func (ekve EncryptionKeyVaultError) Error() string
Error implements the error interface.
func (EncryptionKeyVaultError) Unwrap ¶ added in v1.4.0
func (ekve EncryptionKeyVaultError) Unwrap() error
Unwrap returns the underlying error.
type ErrMapForOrderedArgument ¶ added in v1.5.0
type ErrMapForOrderedArgument struct {
ParamName string
}
ErrMapForOrderedArgument is returned when a map with multiple keys is passed to a CRUD method for an ordered parameter
func (ErrMapForOrderedArgument) Error ¶ added in v1.5.0
func (e ErrMapForOrderedArgument) Error() string
Error implements the error interface.
type IndexModel ¶ added in v0.0.3
type IndexModel struct { // A document describing which keys should be used for the index. It cannot be nil. This must be an order-preserving // type such as bson.D. Map types such as bson.M are not valid. See https://docs.mongodb.com/manual/indexes/#indexes // for examples of valid documents. Keys interface{} // The options to use to create the index. Options *options.IndexOptions }
IndexModel represents a new index to be created.
type IndexOptionsBuilder
deprecated
added in
v0.0.7
type IndexOptionsBuilder struct {
// contains filtered or unexported fields
}
IndexOptionsBuilder specifies options for a new index.
Deprecated: Use the IndexOptions type in the mongo/options package instead.
func NewIndexOptionsBuilder
deprecated
added in
v0.0.7
func NewIndexOptionsBuilder() *IndexOptionsBuilder
NewIndexOptionsBuilder creates a new IndexOptionsBuilder.
Deprecated: Use the Index function in mongo/options instead.
func (*IndexOptionsBuilder) Background
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Background(background bool) *IndexOptionsBuilder
Background specifies a value for the background option.
Deprecated: Use the IndexOptions.SetBackground function in mongo/options instead.
func (*IndexOptionsBuilder) Bits
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Bits(bits int32) *IndexOptionsBuilder
Bits specifies a value for the bits option.
Deprecated: Use the IndexOptions.SetBits function in mongo/options instead.
func (*IndexOptionsBuilder) BucketSize
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) BucketSize(bucketSize int32) *IndexOptionsBuilder
BucketSize specifies a value for the bucketSize option.
Deprecated: Use the IndexOptions.SetBucketSize function in mongo/options instead.
func (*IndexOptionsBuilder) Build
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Build() bson.D
Build finishes constructing an the builder.
Deprecated: Use the IndexOptions type in the mongo/options package instead.
func (*IndexOptionsBuilder) Collation
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilder
Collation specifies a value for the collation option.
Deprecated: Use the IndexOptions.SetCollation function in mongo/options instead.
func (*IndexOptionsBuilder) DefaultLanguage
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguage string) *IndexOptionsBuilder
DefaultLanguage specifies a value for the default_language option.
Deprecated: Use the IndexOptions.SetDefaultLanguage function in mongo/options instead.
func (*IndexOptionsBuilder) ExpireAfterSeconds
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSeconds int32) *IndexOptionsBuilder
ExpireAfterSeconds specifies a value for the expireAfterSeconds option.
Deprecated: Use the IndexOptions.SetExpireAfterSeconds function in mongo/options instead.
func (*IndexOptionsBuilder) LanguageOverride
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilder
LanguageOverride specifies a value for the language_override option.
Deprecated: Use the IndexOptions.SetLanguageOverride function in mongo/options instead.
func (*IndexOptionsBuilder) Max
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Max(max float64) *IndexOptionsBuilder
Max specifies a value for the max option.
Deprecated: Use the IndexOptions.SetMax function in mongo/options instead.
func (*IndexOptionsBuilder) Min
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilder
Min specifies a value for the min option.
Deprecated: Use the IndexOptions.SetMin function in mongo/options instead.
func (*IndexOptionsBuilder) Name
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Name(name string) *IndexOptionsBuilder
Name specifies a value for the name option.
Deprecated: Use the IndexOptions.SetName function in mongo/options instead.
func (*IndexOptionsBuilder) PartialFilterExpression
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilder
PartialFilterExpression specifies a value for the partialFilterExpression option.
Deprecated: Use the IndexOptions.SetPartialFilterExpression function in mongo/options instead.
func (*IndexOptionsBuilder) Sparse
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Sparse(sparse bool) *IndexOptionsBuilder
Sparse specifies a value for the sparse option.
Deprecated: Use the IndexOptions.SetSparse function in mongo/options instead.
func (*IndexOptionsBuilder) SphereVersion
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) SphereVersion(sphereVersion int32) *IndexOptionsBuilder
SphereVersion specifies a value for the 2dsphereIndexVersion option.
Deprecated: Use the IndexOptions.SetSphereVersion function in mongo/options instead.
func (*IndexOptionsBuilder) StorageEngine
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilder
StorageEngine specifies a value for the storageEngine option.
Deprecated: Use the IndexOptions.SetStorageEngine function in mongo/options instead.
func (*IndexOptionsBuilder) TextVersion
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) TextVersion(textVersion int32) *IndexOptionsBuilder
TextVersion specifies a value for the textIndexVersion option.
Deprecated: Use the IndexOptions.SetTextVersion function in mongo/options instead.
func (*IndexOptionsBuilder) Unique
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Unique(unique bool) *IndexOptionsBuilder
Unique specifies a value for the unique option.
Deprecated: Use the IndexOptions.SetUnique function in mongo/options instead.
func (*IndexOptionsBuilder) Version
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Version(version int32) *IndexOptionsBuilder
Version specifies a value for the version option.
Deprecated: Use the IndexOptions.SetVersion function in mongo/options instead.
func (*IndexOptionsBuilder) Weights
deprecated
added in
v0.0.7
func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilder
Weights specifies a value for the weights option.
Deprecated: Use the IndexOptions.SetWeights function in mongo/options instead.
type IndexSpecification ¶ added in v1.5.0
type IndexSpecification struct { // The index name. Name string // The namespace for the index. This is a string in the format "databaseName.collectionName". Namespace string // The keys specification document for the index. KeysDocument bson.Raw // The index version. Version int32 // The length of time, in seconds, for documents to remain in the collection. The default value is 0, which means // that documents will remain in the collection until they're explicitly deleted or the collection is dropped. ExpireAfterSeconds *int32 // If true, the index will only reference documents that contain the fields specified in the index. The default is // false. Sparse *bool // If true, the collection will not accept insertion or update of documents where the index key value matches an // existing value in the index. The default is false. Unique *bool }
IndexSpecification represents an index in a database. This type is returned by the IndexView.ListSpecifications function and is also used in the CollectionSpecification type.
func (*IndexSpecification) UnmarshalBSON ¶ added in v1.5.0
func (i *IndexSpecification) UnmarshalBSON(data []byte) error
UnmarshalBSON implements the bson.Unmarshaler interface.
type IndexView ¶ added in v0.0.3
type IndexView struct {
// contains filtered or unexported fields
}
IndexView is a type that can be used to create, drop, and list indexes on a collection. An IndexView for a collection can be created by a call to Collection.Indexes().
func (IndexView) CreateMany ¶ added in v0.0.3
func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error)
CreateMany executes a createIndexes command to create multiple indexes on the collection and returns the names of the new indexes.
For each IndexModel in the models parameter, the index name can be specified via the Options field. If a name is not given, it will be generated from the Keys document.
The opts parameter can be used to specify options for this operation (see the options.CreateIndexesOptions documentation).
For more information about the command, see https://docs.mongodb.com/manual/reference/command/createIndexes/.
func (IndexView) CreateOne ¶ added in v0.0.3
func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*options.CreateIndexesOptions) (string, error)
CreateOne executes a createIndexes command to create an index on the collection and returns the name of the new index. See the IndexView.CreateMany documentation for more information and an example.
func (IndexView) DropAll ¶ added in v0.0.3
func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOptions) (bson.Raw, error)
DropAll executes a dropIndexes operation to drop all indexes on the collection. If the operation succeeds, this returns a BSON document in the form {nIndexesWas: <int32>}. The "nIndexesWas" field in the response contains the number of indexes that existed prior to the drop.
The opts parameter can be used to specify options for this operation (see the options.DropIndexesOptions documentation).
For more information about the command, see https://docs.mongodb.com/manual/reference/command/dropIndexes/.
func (IndexView) DropOne ¶ added in v0.0.3
func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.DropIndexesOptions) (bson.Raw, error)
DropOne executes a dropIndexes operation to drop an index on the collection. If the operation succeeds, this returns a BSON document in the form {nIndexesWas: <int32>}. The "nIndexesWas" field in the response contains the number of indexes that existed prior to the drop.
The name parameter should be the name of the index to drop. If the name is "*", ErrMultipleIndexDrop will be returned without running the command because doing so would drop all indexes.
The opts parameter can be used to specify options for this operation (see the options.DropIndexesOptions documentation).
For more information about the command, see https://docs.mongodb.com/manual/reference/command/dropIndexes/.
func (IndexView) List ¶ added in v0.0.3
List executes a listIndexes command and returns a cursor over the indexes in the collection.
The opts parameter can be used to specify options for this operation (see the options.ListIndexesOptions documentation).
For more information about the command, see https://docs.mongodb.com/manual/reference/command/listIndexes/.
func (IndexView) ListSpecifications ¶ added in v1.5.0
func (iv IndexView) ListSpecifications(ctx context.Context, opts ...*options.ListIndexesOptions) ([]*IndexSpecification, error)
ListSpecifications executes a List command and returns a slice of returned IndexSpecifications
type InsertManyResult ¶
type InsertManyResult struct {
// The _id values of the inserted documents. Values generated by the driver will be of type primitive.ObjectID.
InsertedIDs []interface{}
}
InsertManyResult is a result type returned by an InsertMany operation.
type InsertOneModel ¶ added in v0.0.16
type InsertOneModel struct {
Document interface{}
}
InsertOneModel is used to insert a single document in a BulkWrite operation.
func NewInsertOneModel ¶ added in v0.0.16
func NewInsertOneModel() *InsertOneModel
NewInsertOneModel creates a new InsertOneModel.
func (*InsertOneModel) SetDocument ¶ added in v0.3.0
func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel
SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field when transformed into BSON, one will be added automatically to the marshalled document. The original document will not be modified.
type InsertOneResult ¶
type InsertOneResult struct {
// The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID.
InsertedID interface{}
}
InsertOneResult is the result type returned by an InsertOne operation.
type ListDatabasesResult ¶ added in v0.0.3
type ListDatabasesResult struct { // A slice containing one DatabaseSpecification for each database matched by the operation's filter. Databases []DatabaseSpecification // The total size of the database files of the returned databases in bytes. // This will be the sum of the SizeOnDisk field for each specification in Databases. TotalSize int64 }
ListDatabasesResult is a result of a ListDatabases operation.
type MarshalError ¶ added in v0.0.15
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 ¶ added in v0.0.15
func (me MarshalError) Error() string
Error implements the error interface.
type MongocryptError ¶ added in v1.2.0
MongocryptError represents an libmongocrypt error during client-side encryption.
func (MongocryptError) Error ¶ added in v1.2.0
func (m MongocryptError) Error() string
Error implements the error interface.
type MongocryptdError ¶ added in v1.2.0
type MongocryptdError struct {
Wrapped error
}
MongocryptdError represents an error while communicating with mongocryptd during client-side encryption.
func (MongocryptdError) Error ¶ added in v1.2.0
func (e MongocryptdError) Error() string
Error implements the error interface.
func (MongocryptdError) Unwrap ¶ added in v1.4.0
func (e MongocryptdError) Unwrap() error
Unwrap returns the underlying error.
type Pipeline ¶ added in v0.0.18
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 ¶ added in v0.0.16
type ReplaceOneModel struct { Collation *options.Collation Upsert *bool Filter interface{} Replacement interface{} Hint interface{} }
ReplaceOneModel is used to replace at most one document in a BulkWrite operation.
func NewReplaceOneModel ¶ added in v0.0.16
func NewReplaceOneModel() *ReplaceOneModel
NewReplaceOneModel creates a new ReplaceOneModel.
func (*ReplaceOneModel) SetCollation ¶ added in v0.3.0
func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will be used.
func (*ReplaceOneModel) SetFilter ¶ added in v0.3.0
func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel
SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing query operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching documents.
func (*ReplaceOneModel) SetHint ¶ added in v1.4.0
func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the index specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option is specified. The driver will return an error if this option is specified during an unacknowledged write operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
func (*ReplaceOneModel) SetReplacement ¶ added in v0.3.0
func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel
SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannot contain any update operators (https://docs.mongodb.com/manual/reference/operator/update/).
func (*ReplaceOneModel) SetUpsert ¶ added in v0.3.0
func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel
SetUpsert specifies whether or not the replacement document should be inserted if no document matching the filter is found. If an upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of the BulkWriteResult.
type ServerError ¶ added in v1.5.0
type ServerError interface { error // HasErrorCode returns true if the error has the specified code. HasErrorCode(int) bool // HasErrorLabel returns true if the error contains the specified label. HasErrorLabel(string) bool // HasErrorMessage returns true if the error contains the specified message. HasErrorMessage(string) bool // HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message. HasErrorCodeWithMessage(int, string) bool // contains filtered or unexported methods }
ServerError is the interface implemented by errors returned from the server. Custom implementations of this interface should not be used in production.
type Session ¶ added in v0.0.10
type Session interface { // Functions to modify session state. 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) EndSession(context.Context) // Functions to retrieve session properties. ClusterTime() bson.Raw OperationTime() *primitive.Timestamp Client() *Client ID() bson.Raw // Functions to modify mutable session properties. 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. If the callback fails, the driver will call AbortTransaction. Because this method must succeed to ensure that server-side resources are properly cleaned up, context deadlines and cancellations will not be respected during this call. For a usage example, see the Client.StartSession method documentation.
ClusterTime, OperationTime, Client, and ID return the session's current cluster time, the session's current operation time, the Client associated with the session, and the ID document associated with the session, respectively. The ID document for a session is in the form {"id": <BSON binary value>}.
EndSession method should abort any existing transactions and close the session.
AdvanceClusterTime advances the cluster time for a session. This method will return an error if the session has ended.
AdvanceOperationTime advances the operation time for a session. This method will return an error if the session has ended.
func SessionFromContext ¶ added in v1.4.0
SessionFromContext extracts the mongo.Session object stored in a Context. This can be used on a SessionContext that was created implicitly through one of the callback-based session APIs or explicitly by calling NewSessionContext. If there is no Session stored in the provided Context, nil is returned.
type SessionContext ¶ added in v0.0.16
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.
There are two ways to create a SessionContext and use it in a session/transaction. The first is to use one of the callback-based functions such as WithSession and UseSession. These functions create a SessionContext and pass it to the provided callback. The other is to use NewSessionContext to explicitly create a SessionContext.
func NewSessionContext ¶ added in v1.4.0
func NewSessionContext(ctx context.Context, sess Session) SessionContext
NewSessionContext creates a new SessionContext associated with the given Context and Session parameters.
type SingleResult ¶ added in v0.1.0
type SingleResult struct {
// contains filtered or unexported fields
}
SingleResult represents a single document returned from an operation. If the operation resulted in an error, all SingleResult methods will return that error. If the operation did not return any documents, all SingleResult methods will return ErrNoDocuments.
func NewSingleResultFromDocument ¶ added in v1.9.0
func NewSingleResultFromDocument(document interface{}, err error, registry *bsoncodec.Registry) *SingleResult
NewSingleResultFromDocument creates a SingleResult with the provided error, registry, and an underlying Cursor pre-loaded with the provided document, error and registry. If no registry is provided, bson.DefaultRegistry will be used. If an error distinct from the one provided occurs during creation of the SingleResult, that error will be stored on the returned SingleResult.
The document parameter must be a non-nil document.
func (*SingleResult) Decode ¶ added in v0.1.0
func (sr *SingleResult) Decode(v interface{}) error
Decode will unmarshal the document represented by this SingleResult into v. If there was an error from the operation that created this SingleResult, that error will be returned. If the operation returned no documents, Decode will return ErrNoDocuments.
If the operation was successful and returned a document, Decode will return any errors from the unmarshalling process without any modification. If v is nil or is a typed nil, an error will be returned.
func (*SingleResult) DecodeBytes ¶ added in v0.1.0
func (sr *SingleResult) DecodeBytes() (bson.Raw, error)
DecodeBytes will return the document represented by this SingleResult as a bson.Raw. If there was an error from the operation that created this SingleResult, both the result and that error will be returned. If the operation returned no documents, this will return (nil, ErrNoDocuments).
func (*SingleResult) Err ¶ added in v0.1.0
func (sr *SingleResult) Err() error
Err returns the error from the operation that created this SingleResult. If the operation was successful but did not return any documents, Err will return ErrNoDocuments. If the operation was successful and returned a document, Err will return nil.
type StreamType ¶ added in v0.1.0
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 ¶ added in v0.0.16
type UpdateManyModel struct { Collation *options.Collation Upsert *bool Filter interface{} Update interface{} ArrayFilters *options.ArrayFilters Hint interface{} }
UpdateManyModel is used to update multiple documents in a BulkWrite operation.
func NewUpdateManyModel ¶ added in v0.0.16
func NewUpdateManyModel() *UpdateManyModel
NewUpdateManyModel creates a new UpdateManyModel.
func (*UpdateManyModel) SetArrayFilters ¶ added in v0.3.0
func (umm *UpdateManyModel) SetArrayFilters(filters options.ArrayFilters) *UpdateManyModel
SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array field.
func (*UpdateManyModel) SetCollation ¶ added in v0.3.0
func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will be used.
func (*UpdateManyModel) SetFilter ¶ added in v0.3.0
func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel
SetFilter specifies a filter to use to select documents to update. The filter must be a document containing query operators. It cannot be nil.
func (*UpdateManyModel) SetHint ¶ added in v1.4.0
func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the index specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option is specified. The driver will return an error if this option is specified during an unacknowledged write operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
func (*UpdateManyModel) SetUpdate ¶ added in v0.3.0
func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel
SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containing update operators (https://docs.mongodb.com/manual/reference/operator/update/). It cannot be nil or empty.
func (*UpdateManyModel) SetUpsert ¶ added in v0.3.0
func (umm *UpdateManyModel) SetUpsert(upsert bool) *UpdateManyModel
SetUpsert specifies whether or not a new document should be inserted if no document matching the filter is found. If an upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of the BulkWriteResult.
type UpdateOneModel ¶ added in v0.0.16
type UpdateOneModel struct { Collation *options.Collation Upsert *bool Filter interface{} Update interface{} ArrayFilters *options.ArrayFilters Hint interface{} }
UpdateOneModel is used to update at most one document in a BulkWrite operation.
func NewUpdateOneModel ¶ added in v0.0.16
func NewUpdateOneModel() *UpdateOneModel
NewUpdateOneModel creates a new UpdateOneModel.
func (*UpdateOneModel) SetArrayFilters ¶ added in v0.3.0
func (uom *UpdateOneModel) SetArrayFilters(filters options.ArrayFilters) *UpdateOneModel
SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array field.
func (*UpdateOneModel) SetCollation ¶ added in v0.3.0
func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel
SetCollation specifies a collation to use for string comparisons. The default is nil, meaning no collation will be used.
func (*UpdateOneModel) SetFilter ¶ added in v0.3.0
func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel
SetFilter specifies a filter to use to select the document to update. The filter must be a document containing query operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching documents.
func (*UpdateOneModel) SetHint ¶ added in v1.4.0
func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel
SetHint specifies the index to use for the operation. This should either be the index name as a string or the index specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option is specified. The driver will return an error if this option is specified during an unacknowledged write operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
func (*UpdateOneModel) SetUpdate ¶ added in v0.3.0
func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel
SetUpdate specifies the modifications to be made to the selected document. The value must be a document containing update operators (https://docs.mongodb.com/manual/reference/operator/update/). It cannot be nil or empty.
func (*UpdateOneModel) SetUpsert ¶ added in v0.3.0
func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel
SetUpsert specifies whether or not a new document should be inserted if no document matching the filter is found. If an upsert is performed, the _id of the upserted document can be retrieved from the UpsertedIDs field of the BulkWriteResult.
type UpdateResult ¶
type UpdateResult struct { MatchedCount int64 // The number of documents matched by the filter. ModifiedCount int64 // The number of documents modified by the operation. UpsertedCount int64 // The number of documents upserted by the operation. UpsertedID interface{} // The _id field of the upserted document, or nil if no upsert was done. }
UpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations.
func (*UpdateResult) UnmarshalBSON ¶
func (result *UpdateResult) UnmarshalBSON(b []byte) error
UnmarshalBSON implements the bson.Unmarshaler interface.
type WriteConcernError ¶ added in v0.0.4
type WriteConcernError struct { Name string Code int Message string Details bson.Raw Raw bson.Raw // The original write concern error from the server response. }
WriteConcernError represents a write concern failure during execution of a write operation. This error type is only returned as part of a WriteException or a BulkWriteException.
func (WriteConcernError) Error ¶ added in v0.0.4
func (wce WriteConcernError) Error() string
Error implements the error interface.
type WriteError ¶ added in v0.0.4
type WriteError struct { // The index of the write in the slice passed to an InsertMany or BulkWrite operation that caused this error. Index int Code int Message string Details bson.Raw // The original write error from the server response. Raw bson.Raw }
WriteError is an error that occurred during execution of a write operation. This error type is only returned as part of a WriteException or BulkWriteException.
func (WriteError) Error ¶ added in v0.0.4
func (we WriteError) Error() string
func (WriteError) HasErrorCode ¶ added in v1.9.0
func (we WriteError) HasErrorCode(code int) bool
HasErrorCode returns true if the error has the specified code.
func (WriteError) HasErrorCodeWithMessage ¶ added in v1.9.0
func (we WriteError) HasErrorCodeWithMessage(code int, message string) bool
HasErrorCodeWithMessage returns true if the error has the specified code and Message contains the specified message.
func (WriteError) HasErrorLabel ¶ added in v1.9.0
func (we WriteError) HasErrorLabel(label string) bool
HasErrorLabel returns true if the error contains the specified label. WriteErrors do not contain labels, so we always return false.
func (WriteError) HasErrorMessage ¶ added in v1.9.0
func (we WriteError) HasErrorMessage(message string) bool
HasErrorMessage returns true if the error contains the specified message.
type WriteErrors ¶ added in v0.0.4
type WriteErrors []WriteError
WriteErrors is a group of write errors that occurred during execution of a write operation.
func (WriteErrors) Error ¶ added in v0.0.4
func (we WriteErrors) Error() string
Error implements the error interface.
type WriteException ¶ added in v0.3.0
type WriteException struct { // The write concern error that occurred, or nil if there was none. WriteConcernError *WriteConcernError // The write errors that occurred during operation execution. WriteErrors WriteErrors // The categories to which the exception belongs. Labels []string // The original server response containing the error. Raw bson.Raw }
WriteException is the error type returned by the InsertOne, DeleteOne, DeleteMany, UpdateOne, UpdateMany, and ReplaceOne operations.
func (WriteException) Error ¶ added in v0.3.0
func (mwe WriteException) Error() string
Error implements the error interface.
func (WriteException) HasErrorCode ¶ added in v1.5.0
func (mwe WriteException) HasErrorCode(code int) bool
HasErrorCode returns true if the error has the specified code.
func (WriteException) HasErrorCodeWithMessage ¶ added in v1.5.0
func (mwe WriteException) HasErrorCodeWithMessage(code int, message string) bool
HasErrorCodeWithMessage returns true if any of the contained errors have the specified code and message.
func (WriteException) HasErrorLabel ¶ added in v1.4.0
func (mwe WriteException) HasErrorLabel(label string) bool
HasErrorLabel returns true if the error contains the specified label.
func (WriteException) HasErrorMessage ¶ added in v1.5.0
func (mwe WriteException) HasErrorMessage(message string) bool
HasErrorMessage returns true if the error contains the specified message.
type WriteModel ¶ added in v0.0.16
type WriteModel interface {
// contains filtered or unexported methods
}
WriteModel is an interface implemented by models that can be used in a BulkWrite operation. Each WriteModel represents a write.
This interface is implemented by InsertOneModel, DeleteOneModel, DeleteManyModel, ReplaceOneModel, UpdateOneModel, and UpdateManyModel. Custom implementations of this interface must not be used.
type XSession
deprecated
added in
v1.2.0
XSession is an unstable interface for internal use only.
Deprecated: This interface is unstable because it provides access to a session.Client object, which exists in the "x" package. It should not be used by applications and may be changed or removed in any release.
Notes ¶
Bugs ¶
ListCollectionSpecifications prevents listing more than 100 collections per database when running against MongoDB version 2.6.
ListCollections prevents listing more than 100 collections per database when running against MongoDB version 2.6.
ListCollectionNames prevents listing more than 100 collections per database when running against MongoDB version 2.6.
Source Files ¶
- batch_cursor.go
- bulk_write.go
- bulk_write_models.go
- change_stream.go
- change_stream_deployment.go
- client.go
- client_encryption.go
- collection.go
- crypt_retrievers.go
- cursor.go
- database.go
- doc.go
- errors.go
- index_options_builder.go
- index_view.go
- mongo.go
- mongocryptd.go
- results.go
- session.go
- single_result.go
- util.go