mongo-go-driver: github.com/mongodb/mongo-go-driver/mongo Index | Files | Directories

package mongo

import "github.com/mongodb/mongo-go-driver/mongo"

Package mongo provides a MongoDB Driver API for Go.

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

client, err := mongo.NewClient("mongodb://foo:bar@localhost:27017")
if err != nil { log.Fatal(err) }
err = client.Connect(context.TODO())
if err != nil { log.Fatal(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(), map[string]string{"hello": "world"})
if err != nil { log.Fatal(err) }
id := res.InsertedID

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

cur, err := collection.Find(context.Background(), nil)
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
for cur.Next(context.Background()) {
   elem := bson.NewDocument()
   err := cur.Decode(elem)
   if err != nil { log.Fatal(err) }
   // do something with elem....
}
if err := cur.Err(); err != nil {
    log.Fatal(err)
}

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

result := bson.NewDocument()
filter := bson.NewDocument(bson.EC.String("hello", "world"))
err := collection.FindOne(context.Background(), filter).Decode(result)
if err != nil { log.Fatal(err) }
// do something with result...

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

Index

Package Files

bulk_write.go change_stream.go client.go collection.go cursor.go database.go doc.go document_result.go errors.go index_options_builder.go index_view.go mongo.go results.go session.go util.go

Variables

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

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

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

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

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

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

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

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

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

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

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

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

var ErrWrongClient = errors.New("session was not created by this client")

ErrWrongClient is returned when a user attempts to pass in a session created by a different client than the method call is using.

func WithSession Uses

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.

type BSONAppender Uses

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

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

type BSONAppenderFunc Uses

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

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

func (BSONAppenderFunc) AppendBSON Uses

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

AppendBSON implements the BSONAppender interface

type BulkWriteError Uses

type BulkWriteError struct {
    WriteError
    Request WriteModel
}

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

func (BulkWriteError) Error Uses

func (bwe BulkWriteError) Error() string

type BulkWriteException Uses

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

BulkWriteException is an error for a bulk write operation.

func (BulkWriteException) Error Uses

func (bwe BulkWriteException) Error() string

type BulkWriteResult Uses

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

BulkWriteResult holds the result of a bulk write operation.

type Client Uses

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

Client performs operations on a given topology.

func Connect Uses

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

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

func NewClient Uses

func NewClient(uri string) (*Client, error)

NewClient creates a new client to connect to a cluster specified by the uri.

func NewClientFromConnString Uses

func NewClientFromConnString(cs connstring.ConnString) (*Client, error)

NewClientFromConnString creates a new client to connect to a cluster, with configuration specified by the connection string.

func NewClientWithOptions Uses

func NewClientWithOptions(uri string, opts ...*options.ClientOptions) (*Client, error)

NewClientWithOptions creates a new client to connect to to a cluster specified by the connection string and the options manually passed in. If the same option is configured in both the connection string and the manual options, the manual option will be ignored.

func (*Client) Connect Uses

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.

func (*Client) ConnectionString Uses

func (c *Client) ConnectionString() string

ConnectionString returns the connection string of the cluster the client is connected to.

func (*Client) Database Uses

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

Database returns a handle for a given database.

func (*Client) Disconnect Uses

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

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

func (*Client) ListDatabaseNames Uses

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

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

func (*Client) ListDatabases Uses

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

ListDatabases returns a ListDatabasesResult.

func (*Client) Ping Uses

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 Uses

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

StartSession starts a new session.

func (*Client) UseSession Uses

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 Uses

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) ValidSession Uses

func (c *Client) ValidSession(sess *session.Client) error

ValidSession returns an error if the session doesn't belong to the client

type Collection Uses

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

Collection performs operations on a given collection.

func (*Collection) Aggregate Uses

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

Aggregate runs an aggregation framework pipeline. A user can supply a custom context to this method.

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

This method uses TransformDocument to turn the pipeline parameter into a *bsonx.Document. See TransformDocument for the list of valid types for pipeline.

func (*Collection) BulkWrite Uses

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

BulkWrite performs a bulk write operation. A custom context can be supplied to this method or nil to default to context.Background().

func (*Collection) Clone Uses

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) Count Uses

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

Count gets the number of documents matching the filter. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) CountDocuments Uses

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

CountDocuments gets the number of documents matching the filter. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses countDocumentsAggregatePipeline to turn the filter parameter and options into aggregate pipeline.

func (*Collection) Database Uses

func (coll *Collection) Database() *Database

Database provides access to the database that contains the collection.

func (*Collection) DeleteMany Uses

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

DeleteMany deletes multiple documents from the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) DeleteOne Uses

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

DeleteOne deletes a single document from the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) Distinct Uses

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. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) Drop Uses

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

Drop drops this collection from database.

func (*Collection) EstimatedDocumentCount Uses

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 Uses

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

Find finds the documents matching a model. A user can supply a custom context to this method.

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) FindOne Uses

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

FindOne returns up to one document that matches the model. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) FindOneAndDelete Uses

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

FindOneAndDelete find a single document and deletes it, returning the original in result. The document to return may be nil.

A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter.

func (*Collection) FindOneAndReplace Uses

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

FindOneAndReplace finds a single document and replaces it, returning either the original or the replaced document. The document to return may be nil.

A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter and replacement parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter and replacement.

func (*Collection) FindOneAndUpdate Uses

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

FindOneAndUpdate finds a single document and updates it, returning either the original or the updated. The document to return may be nil.

A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter and update parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter and update.

func (*Collection) Indexes Uses

func (coll *Collection) Indexes() IndexView

Indexes returns the index view for this collection.

func (*Collection) InsertMany Uses

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

InsertMany inserts the provided documents. A user can supply a custom context to this method.

Currently, batching is not implemented for this operation. Because of this, extremely large sets of documents will not fit into a single BSON document to be sent to the server, so the operation will fail.

This method uses TransformDocument to turn the documents parameter into a *bsonx.Document. See TransformDocument for the list of valid types for documents.

func (*Collection) InsertOne Uses

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

InsertOne inserts a single document into the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the document parameter into a *bsonx.Document. See TransformDocument for the list of valid types for document.

TODO(skriptble): Determine if we should unwrap the value for the InsertOneResult or just return the bsonx.Element or a bsonx.Value.

func (*Collection) Name Uses

func (coll *Collection) Name() string

Name provides access to the name of the collection.

func (*Collection) ReplaceOne Uses

func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{},
    replacement interface{}, opts ...*options.ReplaceOptions) (*UpdateResult, error)

ReplaceOne replaces a single document in the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter and replacement parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter and replacement.

func (*Collection) UpdateMany Uses

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

UpdateMany updates multiple documents in the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter and update parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter and update.

func (*Collection) UpdateOne Uses

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

UpdateOne updates a single document in the collection. A user can supply a custom context to this method, or nil to default to context.Background().

This method uses TransformDocument to turn the filter and update parameter into a *bsonx.Document. See TransformDocument for the list of valid types for filter and update.

func (*Collection) Watch Uses

func (coll *Collection) Watch(ctx context.Context, pipeline interface{},
    opts ...*options.ChangeStreamOptions) (Cursor, 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.

type Cursor Uses

type Cursor interface {

    // Get the ID of the cursor.
    ID() int64

    // Get the next result from the cursor.
    // Returns true if there were no errors and there is a next result.
    Next(context.Context) bool

    Decode(interface{}) error

    DecodeBytes() (bson.Raw, error)

    // Returns the error status of the cursor
    Err() error

    // Close the cursor.
    Close(context.Context) error
}

Cursor instances 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 interface would be:

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

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

	// do something with elem....
}

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

type Database Uses

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

Database performs operations on a given database.

func (*Database) Client Uses

func (db *Database) Client() *Client

Client returns the Client the database was created from.

func (*Database) Collection Uses

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

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

func (*Database) Drop Uses

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

Drop drops this database from mongodb.

func (*Database) ListCollections Uses

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

ListCollections list collections from mongodb database.

func (*Database) Name Uses

func (db *Database) Name() string

Name returns the name of the database.

func (*Database) ReadConcern Uses

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

ReadConcern returns the read concern of this database.

func (*Database) ReadPreference Uses

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

ReadPreference returns the read preference of this database.

func (*Database) RunCommand Uses

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

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

func (*Database) WriteConcern Uses

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

WriteConcern returns the write concern of this database.

type DatabaseSpecification Uses

type DatabaseSpecification struct {
    Name       string
    SizeOnDisk int64
    Empty      bool
}

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

type DeleteManyModel Uses

type DeleteManyModel struct {
    dispatch.DeleteManyModel
}

DeleteManyModel is the write model for deleteMany operations.

func NewDeleteManyModel Uses

func NewDeleteManyModel() *DeleteManyModel

NewDeleteManyModel creates a new DeleteManyModel.

func (*DeleteManyModel) Collation Uses

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

Collation sets the collation for the DeleteManyModel.

func (*DeleteManyModel) Filter Uses

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

Filter sets the filter for the DeleteManyModel.

type DeleteOneModel Uses

type DeleteOneModel struct {
    dispatch.DeleteOneModel
}

DeleteOneModel is the write model for delete operations.

func NewDeleteOneModel Uses

func NewDeleteOneModel() *DeleteOneModel

NewDeleteOneModel creates a new DeleteOneModel.

func (*DeleteOneModel) Collation Uses

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

Collation sets the collation for the DeleteOneModel.

func (*DeleteOneModel) Filter Uses

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

Filter sets the filter for the DeleteOneModel.

type DeleteResult Uses

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

DeleteResult is a result of an DeleteOne operation.

type Dialer Uses

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

Dialer is used to make network connections.

type DocumentResult Uses

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

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

func (*DocumentResult) Decode Uses

func (dr *DocumentResult) 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 DocumentResult then the error will be returned. If there were no returned documents, ErrNoDocuments is returned.

type IndexModel Uses

type IndexModel struct {
    Keys    bsonx.Doc
    Options bsonx.Doc
}

IndexModel contains information about an index.

type IndexOptionsBuilder Uses

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

IndexOptionsBuilder constructs a BSON document for index options

func NewIndexOptionsBuilder Uses

func NewIndexOptionsBuilder() *IndexOptionsBuilder

NewIndexOptionsBuilder creates a new instance of IndexOptionsBuilder

func (*IndexOptionsBuilder) Background Uses

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

Background sets the background option

func (*IndexOptionsBuilder) Bits Uses

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

Bits sets the bits option

func (*IndexOptionsBuilder) BucketSize Uses

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

BucketSize sets the bucketSize option

func (*IndexOptionsBuilder) Build Uses

func (iob *IndexOptionsBuilder) Build() bsonx.Doc

Build returns the BSON document from the builder

func (*IndexOptionsBuilder) Collation Uses

func (iob *IndexOptionsBuilder) Collation(collation bsonx.Doc) *IndexOptionsBuilder

Collation sets the collation option

func (*IndexOptionsBuilder) DefaultLanguage Uses

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

DefaultLanguage sets the defaultLanguage option

func (*IndexOptionsBuilder) ExpireAfterSeconds Uses

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

ExpireAfterSeconds sets the expireAfterSeconds option

func (*IndexOptionsBuilder) LanguageOverride Uses

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

LanguageOverride sets the languageOverride option

func (*IndexOptionsBuilder) Max Uses

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

Max sets the max option

func (*IndexOptionsBuilder) Min Uses

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

Min sets the min option

func (*IndexOptionsBuilder) Name Uses

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

Name sets the name option

func (*IndexOptionsBuilder) PartialFilterExpression Uses

func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression bsonx.Doc) *IndexOptionsBuilder

PartialFilterExpression sets the partialFilterExpression option

func (*IndexOptionsBuilder) Sparse Uses

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

Sparse sets the sparse option

func (*IndexOptionsBuilder) SphereVersion Uses

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

SphereVersion sets the sphereVersion option

func (*IndexOptionsBuilder) StorageEngine Uses

func (iob *IndexOptionsBuilder) StorageEngine(storageEngine bsonx.Doc) *IndexOptionsBuilder

StorageEngine sets the storageEngine option

func (*IndexOptionsBuilder) TextVersion Uses

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

TextVersion sets the textVersion option

func (*IndexOptionsBuilder) Unique Uses

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

Unique sets the unique option

func (*IndexOptionsBuilder) Version Uses

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

Version sets the version option

func (*IndexOptionsBuilder) Weights Uses

func (iob *IndexOptionsBuilder) Weights(weights bsonx.Doc) *IndexOptionsBuilder

Weights sets the weights option

type IndexView Uses

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

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

func (IndexView) CreateMany Uses

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

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

func (IndexView) CreateOne Uses

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

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

func (IndexView) DropAll Uses

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

DropAll drops all indexes in the collection.

func (IndexView) DropOne Uses

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

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

func (IndexView) List Uses

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

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

type InsertManyResult Uses

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

InsertManyResult is a result of an InsertMany operation.

type InsertOneModel Uses

type InsertOneModel struct {
    dispatch.InsertOneModel
}

InsertOneModel is the write model for insert operations.

func NewInsertOneModel Uses

func NewInsertOneModel() *InsertOneModel

NewInsertOneModel creates a new InsertOneModel.

func (*InsertOneModel) Document Uses

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

Document sets the BSON document for the InsertOneModel.

type InsertOneResult Uses

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

InsertOneResult is a result of an InsertOne operation.

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

type ListDatabasesResult Uses

type ListDatabasesResult struct {
    Databases []DatabaseSpecification
    TotalSize int64
}

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

type MarshalError Uses

type MarshalError struct {
    Value interface{}
    Err   error
}

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

func (MarshalError) Error Uses

func (me MarshalError) Error() string

Error implements the error interface.

type Pipeline Uses

type Pipeline []bson.D

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

Example usage:

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

type ReplaceOneModel Uses

type ReplaceOneModel struct {
    dispatch.ReplaceOneModel
}

ReplaceOneModel is the write model for replace operations.

func NewReplaceOneModel Uses

func NewReplaceOneModel() *ReplaceOneModel

NewReplaceOneModel creates a new ReplaceOneModel.

func (*ReplaceOneModel) Collation Uses

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

Collation sets the collation for the ReplaceOneModel.

func (*ReplaceOneModel) Filter Uses

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

Filter sets the filter for the ReplaceOneModel.

func (*ReplaceOneModel) Replacement Uses

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

Replacement sets the replacement document for the ReplaceOneModel.

func (*ReplaceOneModel) Upsert Uses

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

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

type Session Uses

type Session interface {
    EndSession(context.Context)
    StartTransaction(...*options.TransactionOptions) error
    AbortTransaction(context.Context) error
    CommitTransaction(context.Context) error
    ClusterTime() bsonx.Doc
    AdvanceClusterTime(bsonx.Doc) error
    OperationTime() *primitive.Timestamp
    AdvanceOperationTime(*primitive.Timestamp) error
    // 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 Uses

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.

type UpdateManyModel Uses

type UpdateManyModel struct {
    dispatch.UpdateManyModel
}

UpdateManyModel is the write model for updateMany operations.

func NewUpdateManyModel Uses

func NewUpdateManyModel() *UpdateManyModel

NewUpdateManyModel creates a new UpdateManyModel.

func (*UpdateManyModel) ArrayFilters Uses

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

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

func (*UpdateManyModel) Collation Uses

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

Collation sets the collation for the UpdateManyModel.

func (*UpdateManyModel) Filter Uses

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

Filter sets the filter for the UpdateManyModel.

func (*UpdateManyModel) Update Uses

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

Update sets the update document for the UpdateManyModel.

func (*UpdateManyModel) Upsert Uses

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

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

type UpdateOneModel Uses

type UpdateOneModel struct {
    dispatch.UpdateOneModel
}

UpdateOneModel is the write model for update operations.

func NewUpdateOneModel Uses

func NewUpdateOneModel() *UpdateOneModel

NewUpdateOneModel creates a new UpdateOneModel.

func (*UpdateOneModel) ArrayFilters Uses

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

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

func (*UpdateOneModel) Collation Uses

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

Collation sets the collation for the UpdateOneModel.

func (*UpdateOneModel) Filter Uses

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

Filter sets the filter for the UpdateOneModel.

func (*UpdateOneModel) Update Uses

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

Update sets the update document for the UpdateOneModel.

func (*UpdateOneModel) Upsert Uses

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

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

type UpdateResult Uses

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

UpdateResult is a result of an update operation.

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

func (*UpdateResult) UnmarshalBSON Uses

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

UnmarshalBSON implements the bson.Unmarshaler interface.

type WriteConcernError Uses

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

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

func (WriteConcernError) Error Uses

func (wce WriteConcernError) Error() string

type WriteError Uses

type WriteError struct {
    Index   int
    Code    int
    Message string
}

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

func (WriteError) Error Uses

func (we WriteError) Error() string

type WriteErrors Uses

type WriteErrors []WriteError

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

func (WriteErrors) Error Uses

func (we WriteErrors) Error() string

type WriteModel Uses

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

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

Directories

PathSynopsis
gridfs
readconcern
readpref
writeconcern

Package mongo imports 27 packages (graph) and is imported by 43 packages. Updated 2018-11-15. Refresh now. Tools for package owners.