mongo

package
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2019 License: Apache-2.0 Imports: 30 Imported by: 0

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 the NewClient and Connect functions:

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

This will create a new client and start monitoring the MongoDB server on localhost. The Database and Collection types can be used to access the database:

collection := client.Database("baz").Collection("qux")

A Collection can be used to query the database or insert documents:

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID

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

cur, err := collection.Find(context.Background(), bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
  // To decode into a struct, use cursor.Decode()
  result := struct{
    Foo string
    Bar int32
  }{}
  err := cur.Decode(&result)
  if err != nil { log.Fatal(err) }
  // do something with result...

  // To get the raw bson bytes use cursor.Current
  raw := cur.Current
  // do something with raw...
}
if err := cur.Err(); err != nil {
  return err
}

Methods that only return a single document will return a *SingleResult, which works like a *sql.Row:

	  result := struct{
	  	Foo string
	  	Bar int32
	  }{}
   filter := bson.D{{"hello", "world"}}
   err := collection.FindOne(context.Background(), filter).Decode(&result)
   if err != nil { return err }
   // do something with result...

All Client, Collection, and Database methods that take parameters of type interface{} will return ErrNilDocument if nil is passed in for an interface{}.

Additional examples can be found under the examples directory in the driver's repository and on the MongoDB website.

Potential DNS Issues

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

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

Index

Examples

Constants

This section is empty.

Variables

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ErrUnacknowledgedWrite is returned from functions that have an unacknowledged write concern.

View Source
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 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. This method is deprecated and does not have any stability guarantees. It may be removed in the future.

func WithSession added in v0.0.16

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

WithSession allows a user to start a session themselves and manage its lifetime. The only way to provide a session to a CRUD method is to invoke that CRUD method with the mongo.SessionContext within the closure. The mongo.SessionContext can be used as a regular context, so methods like context.WithDeadline and context.WithTimeout are supported.

If the context.Context already has a mongo.Session attached, that mongo.Session will be replaced with the one provided.

Errors returned from the closure are transparently returned from this function.

Types

type BSONAppender added in v0.0.15

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

BSONAppender is an interface implemented by types that can marshal a provided type into BSON bytes and append those bytes to the provided []byte. The AppendBSON can return a non-nil error and non-nil []byte. The AppendBSON method may also write incomplete BSON to the []byte.

type BSONAppenderFunc added in v0.0.15

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

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

func (BSONAppenderFunc) AppendBSON 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
	Request WriteModel
}

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

func (BulkWriteError) Error added in v0.0.4

func (bwe BulkWriteError) Error() string

type BulkWriteException added in v0.0.16

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

BulkWriteException is an error for a bulk write operation.

func (BulkWriteException) Error added in v0.0.16

func (bwe BulkWriteException) Error() string

type BulkWriteResult added in v0.0.16

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

BulkWriteResult holds the result of a bulk write operation.

type ChangeStream added in v0.3.0

type ChangeStream struct {
	Current bson.Raw
	// contains filtered or unexported fields
}

ChangeStream instances iterate a stream of change documents. Each document can be decoded via the Decode method. Resume tokens should be retrieved via the ResumeToken method and can be stored to resume the change stream at a specific point in time.

A typical usage of the ChangeStream type would be:

func (*ChangeStream) Close added in v0.3.0

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

Close closes this cursor.

func (*ChangeStream) Decode added in v0.3.0

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

Decode will decode the current document into val.

func (*ChangeStream) Err added in v0.3.0

func (cs *ChangeStream) Err() error

Err returns the current error.

func (*ChangeStream) ID added in v0.3.0

func (cs *ChangeStream) ID() int64

ID returns the cursor ID for this change stream.

func (*ChangeStream) Next added in v0.3.0

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

Next gets the next result from this change stream. Returns true if there were no errors and the next result is available for decoding.

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.

type Client

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

Client performs operations on a given topology.

func Connect added in v0.0.3

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

Connect creates a new Client and then initializes it using the Connect method.

func NewClient

func NewClient(opts ...*options.ClientOptions) (*Client, error)

NewClient creates a new client to connect to a cluster 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

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

Connect initializes the Client by starting background monitoring goroutines. This method must be called before a Client can be used.

Example
client, err := NewClient(options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))
if err != nil {
	return
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
	return
}

return
Output:

func (*Client) Database

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

Database returns a handle for a given database.

func (*Client) Disconnect added in v0.0.3

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

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

func (*Client) ListDatabaseNames added in v0.0.3

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

ListDatabaseNames returns a slice containing the names of all of the databases on the server.

func (*Client) ListDatabases added in v0.0.3

func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult, error)

ListDatabases returns a ListDatabasesResult.

func (*Client) Ping added in v0.0.14

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

Ping verifies that the client can connect to the topology. If readPreference is nil then will use the client's default read preference.

func (*Client) StartSession added in v0.0.10

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

StartSession starts a new session.

func (*Client) UseSession added in v0.0.16

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

UseSession creates a default session, that is only valid for the lifetime of the closure. No cleanup outside of closing the session is done upon exiting the closure. This means that an outstanding transaction will be aborted, even if the closure returns an error.

If ctx already contains a mongo.Session, that mongo.Session will be replaced with the newly created mongo.Session.

Errors returned from the closure are transparently returned from this method.

func (*Client) UseSessionWithOptions added in v0.0.16

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

UseSessionWithOptions works like UseSession but allows the caller to specify the options used 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 cursor used to receive information of changes to the client. This method is preferred to running a raw aggregation with a $changeStream stage because it supports resumability in the case of some errors. The client must have read concern majority or no read concern for a change stream to be created successfully.

type Collection

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

Collection performs operations on a given collection.

func (*Collection) Aggregate

func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{},
	opts ...*options.AggregateOptions) (*Cursor, error)

Aggregate runs an aggregation framework pipeline.

See https://docs.mongodb.com/manual/aggregation/.

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.

See https://docs.mongodb.com/manual/core/bulk-write-operations/.

func (*Collection) Clone added in v0.0.9

func (coll *Collection) Clone(opts ...*options.CollectionOptions) (*Collection, error)

Clone creates a copy of this collection with updated options, if any are given.

func (*Collection) CountDocuments added in v0.0.11

func (coll *Collection) CountDocuments(ctx context.Context, filter interface{},
	opts ...*options.CountOptions) (int64, error)

CountDocuments gets the number of documents matching the filter. For a fast count of the total documents in a collection see EstimatedDocumentCount.

func (*Collection) Database added in v0.0.15

func (coll *Collection) Database() *Database

Database provides access to the database that contains the collection.

func (*Collection) DeleteMany

func (coll *Collection) DeleteMany(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*DeleteResult, error)

DeleteMany deletes multiple documents from the collection.

func (*Collection) DeleteOne

func (coll *Collection) DeleteOne(ctx context.Context, filter interface{},
	opts ...*options.DeleteOptions) (*DeleteResult, error)

DeleteOne deletes a single document from the collection.

func (*Collection) Distinct

func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{},
	opts ...*options.DistinctOptions) ([]interface{}, error)

Distinct finds the distinct values for a specified field across a single collection.

func (*Collection) Drop added in v0.0.4

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

Drop drops this collection from database.

func (*Collection) EstimatedDocumentCount added in v0.0.11

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

EstimatedDocumentCount gets an estimate of the count of documents in a collection using collection metadata.

func (*Collection) Find

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

Find finds the documents matching a model.

func (*Collection) FindOne

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

FindOne returns up to one document that matches the model.

func (*Collection) FindOneAndDelete

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

FindOneAndDelete find a single document and deletes it, returning the original in result.

func (*Collection) FindOneAndReplace

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

FindOneAndReplace finds a single document and replaces it, returning either the original or the replaced document.

func (*Collection) FindOneAndUpdate

func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{},
	update interface{}, opts ...*options.FindOneAndUpdateOptions) *SingleResult

FindOneAndUpdate finds a single document and updates it, returning either the original or the updated.

func (*Collection) Indexes added in v0.0.3

func (coll *Collection) Indexes() IndexView

Indexes returns the index view for this collection.

func (*Collection) InsertMany

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

InsertMany inserts the provided documents.

func (*Collection) InsertOne

func (coll *Collection) InsertOne(ctx context.Context, document interface{},
	opts ...*options.InsertOneOptions) (*InsertOneResult, error)

InsertOne inserts a single document into the collection.

func (*Collection) Name added in v0.0.4

func (coll *Collection) Name() string

Name provides access to 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 replaces a single document in the collection.

func (*Collection) UpdateMany

func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*UpdateResult, error)

UpdateMany updates multiple documents in the collection.

func (*Collection) UpdateOne

func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},
	opts ...*options.UpdateOptions) (*UpdateResult, error)

UpdateOne updates a single document in the collection.

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 cursor used to receive notifications of changes to the collection.

This method is preferred to running a raw aggregation with a $changeStream stage because it supports resumability in the case of some errors. The collection must have read concern majority or no read concern for a change stream to be created successfully.

type CommandError added in v1.0.0

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

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

func (CommandError) Error added in v1.0.0

func (e CommandError) Error() string

Error implements the error interface.

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) IsMaxTimeMSExpiredError added in v1.1.0

func (e CommandError) IsMaxTimeMSExpiredError() bool

IsMaxTimeMSExpiredError indicates if the error is a MaxTimeMSExpiredError.

type Cursor

type Cursor struct {
	// Current is the BSON bytes of the current document. This property is only valid until the next
	// call to Next or Close. If continued access is required to the bson.Raw, you must make a copy
	// of it.
	Current bson.Raw
	// contains filtered or unexported fields
}

Cursor is used to iterate a stream of documents. Each document is decoded into the result according to the rules of the bson package.

A typical usage of the Cursor type would be:

var cur *Cursor
ctx := context.Background()
defer cur.Close(ctx)

for cur.Next(ctx) {
	elem := &bson.D{}
	if err := cur.Decode(elem); err != nil {
		log.Fatal(err)
	}

	// do something with elem....
}

if err := cur.Err(); err != nil {
	log.Fatal(err)
}

func (*Cursor) All added in v1.1.0

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

All iterates the cursor and decodes each document into results. The results parameter must be a pointer to a slice. The slice pointed to by results will be completely overwritten. If the cursor has been iterated, any previously iterated documents will not be included in results.

func (*Cursor) Close added in v0.0.2

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

Close closes this cursor.

func (*Cursor) Decode added in v0.0.2

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

Decode will decode the current document into val. If val is nil or is a typed nil, an error will be returned.

func (*Cursor) Err added in v0.0.2

func (c *Cursor) Err() error

Err returns the current error.

func (*Cursor) ID added in v0.0.2

func (c *Cursor) ID() int64

ID returns the ID of this cursor.

func (*Cursor) Next added in v0.0.2

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

Next gets the next result from this cursor. Returns true if there were no errors and the next result is available for decoding.

type Database

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

Database performs operations on a given database.

func (*Database) Aggregate added in v1.1.0

func (db *Database) Aggregate(ctx context.Context, pipeline interface{},
	opts ...*options.AggregateOptions) (*Cursor, error)

Aggregate runs an aggregation framework pipeline.

See https://docs.mongodb.com/manual/aggregation/.

func (*Database) Client

func (db *Database) Client() *Client

Client returns the Client the database was created from.

func (*Database) Collection

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

Collection gets a handle for a given collection in the database.

func (*Database) Drop added in v0.0.4

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

Drop drops this database from mongodb.

func (*Database) ListCollectionNames added in v1.1.0

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

ListCollectionNames returns a slice containing the names of all of the collections on the server.

func (*Database) ListCollections added in v0.0.6

func (db *Database) ListCollections(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (*Cursor, error)

ListCollections returns a cursor over the collections in a database.

func (*Database) Name

func (db *Database) Name() string

Name returns the name of the database.

func (*Database) ReadConcern added in v0.0.13

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

ReadConcern returns the read concern of this database.

func (*Database) ReadPreference added in v0.0.13

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

ReadPreference returns the read preference of this database.

func (*Database) RunCommand

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

RunCommand runs a command on the database. A user can supply a custom context to this method, or nil to default to context.Background().

Example

Individual commands can be sent to the server and response retrieved via run command.

var db *Database
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := db.RunCommand(ctx, bson.D{{"ping", 1}}).Err()
if err != nil {
	return
}
return
Output:

func (*Database) RunCommandCursor added in v0.1.0

func (db *Database) RunCommandCursor(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor, error)

RunCommandCursor runs a command on the database and returns a cursor over the resulting reader. A user can supply a custom context to this method, or nil to default to context.Background().

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 cursor used to receive information of changes to the database. This method is preferred to running a raw aggregation with a $changeStream stage because it supports resumability in the case of some errors. The database must have read concern majority or no read concern for a change stream to be created successfully.

func (*Database) WriteConcern added in v0.0.13

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

WriteConcern returns the write concern of this database.

type DatabaseSpecification added in v0.0.3

type DatabaseSpecification struct {
	Name       string
	SizeOnDisk int64
	Empty      bool
}

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

type DeleteManyModel added in v0.0.16

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

DeleteManyModel is the write model for deleteMany operations.

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 sets the collation for the DeleteManyModel.

func (*DeleteManyModel) SetFilter added in v0.3.0

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

SetFilter sets the filter for the DeleteManyModel.

type DeleteOneModel added in v0.0.16

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

DeleteOneModel is the write model for delete operations.

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 sets the collation for the DeleteOneModel.

func (*DeleteOneModel) SetFilter added in v0.3.0

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

SetFilter sets the filter for the DeleteOneModel.

type DeleteResult

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

DeleteResult is a result of an DeleteOne operation.

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 IndexModel added in v0.0.3

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

IndexModel contains information about an index.

type IndexOptionsBuilder added in v0.0.7

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

IndexOptionsBuilder constructs a BSON document for index options

func NewIndexOptionsBuilder added in v0.0.7

func NewIndexOptionsBuilder() *IndexOptionsBuilder

NewIndexOptionsBuilder creates a new instance of IndexOptionsBuilder

func (*IndexOptionsBuilder) Background added in v0.0.7

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

Background sets the background option

func (*IndexOptionsBuilder) Bits added in v0.0.7

Bits sets the bits option

func (*IndexOptionsBuilder) BucketSize added in v0.0.7

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

BucketSize sets the bucketSize option

func (*IndexOptionsBuilder) Build added in v0.0.7

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

Build returns the BSON document from the builder

func (*IndexOptionsBuilder) Collation added in v0.0.7

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

Collation sets the collation option

func (*IndexOptionsBuilder) DefaultLanguage added in v0.0.7

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

DefaultLanguage sets the defaultLanguage option

func (*IndexOptionsBuilder) ExpireAfterSeconds added in v0.0.7

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

ExpireAfterSeconds sets the expireAfterSeconds option

func (*IndexOptionsBuilder) LanguageOverride added in v0.0.7

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

LanguageOverride sets the languageOverride option

func (*IndexOptionsBuilder) Max added in v0.0.7

Max sets the max option

func (*IndexOptionsBuilder) Min added in v0.0.7

Min sets the min option

func (*IndexOptionsBuilder) Name added in v0.0.7

Name sets the name option

func (*IndexOptionsBuilder) PartialFilterExpression added in v0.0.7

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

PartialFilterExpression sets the partialFilterExpression option

func (*IndexOptionsBuilder) Sparse added in v0.0.7

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

Sparse sets the sparse option

func (*IndexOptionsBuilder) SphereVersion added in v0.0.7

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

SphereVersion sets the sphereVersion option

func (*IndexOptionsBuilder) StorageEngine added in v0.0.7

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

StorageEngine sets the storageEngine option

func (*IndexOptionsBuilder) TextVersion added in v0.0.7

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

TextVersion sets the textVersion option

func (*IndexOptionsBuilder) Unique added in v0.0.7

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

Unique sets the unique option

func (*IndexOptionsBuilder) Version added in v0.0.7

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

Version sets the version option

func (*IndexOptionsBuilder) Weights added in v0.0.7

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

Weights sets the weights option

type IndexView added in v0.0.3

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

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

func (IndexView) CreateMany added in v0.0.3

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

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

func (IndexView) CreateOne added in v0.0.3

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

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

func (IndexView) DropAll added in v0.0.3

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

DropAll drops all indexes in the collection.

func (IndexView) DropOne added in v0.0.3

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

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

func (IndexView) List added in v0.0.3

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

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

type InsertManyResult

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

InsertManyResult is a result of an InsertMany operation.

type InsertOneModel added in v0.0.16

type InsertOneModel struct {
	Document interface{}
}

InsertOneModel is the write model for insert operations.

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 sets the BSON document for the InsertOneModel.

type InsertOneResult

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

InsertOneResult is a result of an InsertOne operation.

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

type ListDatabasesResult added in v0.0.3

type ListDatabasesResult struct {
	Databases []DatabaseSpecification
	TotalSize int64
}

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

type MarshalError 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 Pipeline added in v0.0.18

type Pipeline []bson.D

Pipeline is a type that makes creating aggregation pipelines easier. It is a helper and is intended for serializing to BSON.

Example usage:

mongo.Pipeline{
	{{"$group", bson.D{{"_id", "$state"}, {"totalPop", bson.D{{"$sum", "$pop"}}}}}},
	{{"$match", bson.D{{"totalPop", bson.D{{"$gte", 10*1000*1000}}}}}},
}

type ReplaceOneModel added in v0.0.16

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

ReplaceOneModel is the write model for replace operations.

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 sets the collation for the ReplaceOneModel.

func (*ReplaceOneModel) SetFilter added in v0.3.0

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

SetFilter sets the filter for the ReplaceOneModel.

func (*ReplaceOneModel) SetReplacement added in v0.3.0

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

SetReplacement sets the replacement document for the ReplaceOneModel.

func (*ReplaceOneModel) SetUpsert added in v0.3.0

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

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

type Session added in v0.0.10

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

Session is the interface that represents a sequential set of operations executed. Instances of this interface can be used to use transactions against the server and to enable causally consistent behavior for applications.

type SessionContext added in v0.0.16

type SessionContext interface {
	context.Context
	Session
}

SessionContext is a hybrid interface. It combines a context.Context with a mongo.Session. This type can be used as a regular context.Context or Session type. It is not goroutine safe and should not be used in multiple goroutines concurrently.

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 returned an error, the Err method of SingleResult will return that error.

func (*SingleResult) Decode added in v0.1.0

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

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

func (*SingleResult) DecodeBytes added in v0.1.0

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

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

func (*SingleResult) Err added in v0.1.0

func (sr *SingleResult) Err() error

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

type StreamType added in v0.1.0

type StreamType uint8

StreamType represents the type of a change stream.

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 whole client.

type UpdateManyModel added in v0.0.16

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

UpdateManyModel is the write model for updateMany operations.

func NewUpdateManyModel 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 specifying to which array elements an update should apply.

func (*UpdateManyModel) SetCollation added in v0.3.0

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

SetCollation sets the collation for the UpdateManyModel.

func (*UpdateManyModel) SetFilter added in v0.3.0

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

SetFilter sets the filter for the UpdateManyModel.

func (*UpdateManyModel) SetUpdate added in v0.3.0

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

SetUpdate sets the update document for the UpdateManyModel.

func (*UpdateManyModel) SetUpsert added in v0.3.0

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

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

type UpdateOneModel added in v0.0.16

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

UpdateOneModel is the write model for update operations.

func NewUpdateOneModel 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 specifying to which array elements an update should apply.

func (*UpdateOneModel) SetCollation added in v0.3.0

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

SetCollation sets the collation for the UpdateOneModel.

func (*UpdateOneModel) SetFilter added in v0.3.0

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

SetFilter sets the filter for the UpdateOneModel.

func (*UpdateOneModel) SetUpdate added in v0.3.0

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

SetUpdate sets the update document for the UpdateOneModel.

func (*UpdateOneModel) SetUpsert added in v0.3.0

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

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

type UpdateResult

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

UpdateResult is a result of an update operation.

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

func (*UpdateResult) UnmarshalBSON

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
}

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

func (WriteConcernError) Error added in v0.0.4

func (wce WriteConcernError) Error() string

type WriteError added in v0.0.4

type WriteError struct {
	Index   int
	Code    int
	Message string
}

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

func (WriteError) Error added in v0.0.4

func (we WriteError) Error() string

type WriteErrors added in v0.0.4

type WriteErrors []WriteError

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

func (WriteErrors) Error added in v0.0.4

func (we WriteErrors) Error() string

type WriteException added in v0.3.0

type WriteException struct {
	WriteConcernError *WriteConcernError
	WriteErrors       WriteErrors
}

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

func (WriteException) Error added in v0.3.0

func (mwe WriteException) Error() string

type WriteModel added in v0.0.16

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL