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 function:
client, err := mongo.NewClient("mongodb://foo:bar@localhost:27017") 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 ¶
- Variables
- func TransformDocument(document interface{}) (*bson.Document, error)
- type Client
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) ConnectionString() string
- func (c *Client) Database(name string) *Database
- func (c *Client) Disconnect(ctx context.Context) error
- func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}) ([]string, error)
- func (c *Client) ListDatabases(ctx context.Context, filter interface{}) (ListDatabasesResult, error)
- type ClientOptions
- func (co *ClientOptions) AppName(s string) *ClientOptions
- func (co *ClientOptions) AuthMechanism(s string) *ClientOptions
- func (co *ClientOptions) AuthMechanismProperties(m map[string]string) *ClientOptions
- func (co *ClientOptions) AuthSource(s string) *ClientOptions
- func (co *ClientOptions) ConnectTimeout(d time.Duration) *ClientOptions
- func (co *ClientOptions) Dialer(d Dialer) *ClientOptions
- func (co *ClientOptions) HeartbeatInterval(d time.Duration) *ClientOptions
- func (co *ClientOptions) Hosts(s []string) *ClientOptions
- func (co *ClientOptions) Journal(b bool) *ClientOptions
- func (co *ClientOptions) LocalThreshold(d time.Duration) *ClientOptions
- func (co *ClientOptions) MaxConnIdleTime(d time.Duration) *ClientOptions
- func (co *ClientOptions) MaxConnsPerHost(u uint16) *ClientOptions
- func (co *ClientOptions) MaxIdleConnsPerHost(u uint16) *ClientOptions
- func (co *ClientOptions) Password(s string) *ClientOptions
- func (co *ClientOptions) ReadConcernLevel(s string) *ClientOptions
- func (co *ClientOptions) ReadPreference(s string) *ClientOptions
- func (co *ClientOptions) ReadPreferenceTagSets(m []map[string]string) *ClientOptions
- func (co *ClientOptions) ReplicaSet(s string) *ClientOptions
- func (co *ClientOptions) SSL(b bool) *ClientOptions
- func (co *ClientOptions) SSLCaFile(s string) *ClientOptions
- func (co *ClientOptions) SSLClientCertificateKeyFile(s string) *ClientOptions
- func (co *ClientOptions) SSLClientCertificateKeyPassword(s func() string) *ClientOptions
- func (co *ClientOptions) SSLInsecure(b bool) *ClientOptions
- func (co *ClientOptions) ServerSelectionTimeout(d time.Duration) *ClientOptions
- func (co *ClientOptions) Single(b bool) *ClientOptions
- func (co *ClientOptions) SocketTimeout(d time.Duration) *ClientOptions
- func (co *ClientOptions) Username(s string) *ClientOptions
- func (co *ClientOptions) WNumber(i int) *ClientOptions
- func (co *ClientOptions) WString(s string) *ClientOptions
- func (co *ClientOptions) WTimeout(d time.Duration) *ClientOptions
- type Collection
- func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...options.AggregateOptioner) (Cursor, error)
- func (coll *Collection) Count(ctx context.Context, filter interface{}, opts ...options.CountOptioner) (int64, error)
- func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...options.DeleteOptioner) (*DeleteResult, error)
- func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...options.DeleteOptioner) (*DeleteResult, error)
- func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, ...) ([]interface{}, error)
- func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...options.FindOptioner) (Cursor, error)
- func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...options.FindOneOptioner) *DocumentResult
- func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, ...) *DocumentResult
- func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, ...) *DocumentResult
- func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, ...) *DocumentResult
- 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.InsertOneOptioner) (*InsertOneResult, error)
- func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement 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{}, ...) (Cursor, error)
- type Cursor
- type Database
- type DatabaseSpecification
- type DeleteResult
- type Dialer
- type DocumentResult
- type IndexModel
- type IndexView
- func (iv IndexView) CreateMany(ctx context.Context, models ...IndexModel) ([]string, error)
- func (iv IndexView) CreateOne(ctx context.Context, model IndexModel) (string, error)
- func (iv IndexView) DropAll(ctx context.Context) (bson.Reader, error)
- func (iv IndexView) DropOne(ctx context.Context, name string) (bson.Reader, error)
- func (iv IndexView) List(ctx context.Context) (Cursor, error)
- type InsertManyResult
- type InsertOneResult
- type ListDatabasesResult
- type Options
- func (Options) AllowDiskUse(b bool) options.OptAllowDiskUse
- func (Options) AllowPartialResults(b bool) options.OptAllowPartialResults
- func (Options) ArrayFilters(filters ...interface{}) (options.OptArrayFilters, error)
- func (Options) BatchSize(i int32) options.OptBatchSize
- func (Options) BypassDocumentValidation(b bool) options.OptBypassDocumentValidation
- func (Options) Collation(collation *options.Collation) options.OptCollation
- func (Options) Comment(s string) options.OptComment
- func (Options) CursorType(cursorType options.CursorType) options.OptCursorType
- func (Options) FullDocument(fullDocument string) options.OptFullDocument
- func (Options) Hint(hint interface{}) (options.OptHint, error)
- func (Options) Limit(i int64) options.OptLimit
- func (Options) Max(max interface{}) (options.OptMax, error)
- func (Options) MaxAwaitTime(duration time.Duration) options.OptMaxAwaitTime
- func (Options) MaxScan(i int64) options.OptMaxScan
- func (Options) MaxTime(duration time.Duration) options.OptMaxTime
- func (Options) Min(min interface{}) (options.OptMin, error)
- func (Options) NoCursorTimeout(b bool) options.OptNoCursorTimeout
- func (Options) OplogReplay(b bool) options.OptOplogReplay
- func (Options) Ordered(b bool) options.OptOrdered
- func (Options) Projection(projection interface{}) (options.OptProjection, error)
- func (Options) ReadConcern(readConcern *readconcern.ReadConcern) (options.OptReadConcern, error)
- func (Options) ResumeAfter(token *bson.Document) options.OptResumeAfter
- func (Options) ReturnDocument(returnDocument options.ReturnDocument) options.OptReturnDocument
- func (Options) ReturnKey(b bool) options.OptReturnKey
- func (Options) ShowRecordID(b bool) options.OptShowRecordID
- func (Options) Skip(i int64) options.OptSkip
- func (Options) Snapshot(b bool) options.OptSnapshot
- func (Options) Sort(sort interface{}) (options.OptSort, error)
- func (Options) Upsert(b bool) options.OptUpsert
- func (Options) WriteConcern(writeConcern *writeconcern.WriteConcern) (options.OptWriteConcern, error)
- type UpdateResult
Constants ¶
This section is empty.
Variables ¶
var ClientOpt = &ClientOptions{}
ClientOpt is a convenience variable provided for access to ClientOptions methods.
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.
Functions ¶
func TransformDocument ¶
TransformDocument handles transforming a document of an allowable type into a *bson.Document. This method is called directly after most methods that have one or more parameters that are documents.
The supported types for document are:
bson.Marshaler bson.DocumentMarshaler bson.Reader []byte (must be a valid BSON document) io.Reader (only 1 BSON document will be read) A custom struct type
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client performs operations on a given topology.
func Connect ¶ added in v0.0.3
Connect creates a new Client and then initializes it using the Connect method.
func NewClientFromConnString ¶
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 ¶ added in v0.0.3
func NewClientWithOptions(uri string, opts *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 ¶ added in v0.0.3
Connect initializes the Client by starting background monitoring goroutines. This method must be called before a Client can be used.
func (*Client) ConnectionString ¶
ConnectionString returns the connection string of the cluster the client is connected to.
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
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{}) (ListDatabasesResult, error)
ListDatabases returns a ListDatabasesResult.
type ClientOptions ¶ added in v0.0.3
type ClientOptions struct {
// contains filtered or unexported fields
}
ClientOptions is used as a namespace for mongo.Client option constructors.
func (*ClientOptions) AppName ¶ added in v0.0.3
func (co *ClientOptions) AppName(s string) *ClientOptions
AppName specifies the client application name. This value is used by MongoDB when it logs connection information and profile information, such as slow queries.
func (*ClientOptions) AuthMechanism ¶ added in v0.0.3
func (co *ClientOptions) AuthMechanism(s string) *ClientOptions
AuthMechanism indicates the mechanism to use for authentication.
Supported values include "SCRAM-SHA-1", "MONGODB-CR", "PLAIN", "GSSAPI", and "MONGODB-X509".
func (*ClientOptions) AuthMechanismProperties ¶ added in v0.0.3
func (co *ClientOptions) AuthMechanismProperties(m map[string]string) *ClientOptions
AuthMechanismProperties specifies additional configuration options which may be used by certain authentication mechanisms.
func (*ClientOptions) AuthSource ¶ added in v0.0.3
func (co *ClientOptions) AuthSource(s string) *ClientOptions
AuthSource specifies the database to authenticate against.
func (*ClientOptions) ConnectTimeout ¶ added in v0.0.3
func (co *ClientOptions) ConnectTimeout(d time.Duration) *ClientOptions
ConnectTimeout specifies the timeout for an initial connection to a server.
func (*ClientOptions) Dialer ¶ added in v0.0.3
func (co *ClientOptions) Dialer(d Dialer) *ClientOptions
Dialer specifies a custom dialer used to dial new connections to a server.
func (*ClientOptions) HeartbeatInterval ¶ added in v0.0.3
func (co *ClientOptions) HeartbeatInterval(d time.Duration) *ClientOptions
HeartbeatInterval specifies the interval to wait between server monitoring checks.
func (*ClientOptions) Hosts ¶ added in v0.0.3
func (co *ClientOptions) Hosts(s []string) *ClientOptions
Hosts specifies the initial list of addresses from which to discover the rest of the cluster.
func (*ClientOptions) Journal ¶ added in v0.0.3
func (co *ClientOptions) Journal(b bool) *ClientOptions
Journal specifies the "j" field of the default write concern to set on the Client.
func (*ClientOptions) LocalThreshold ¶ added in v0.0.3
func (co *ClientOptions) LocalThreshold(d time.Duration) *ClientOptions
LocalThreshold specifies how far to distribute queries, beyond the server with the fastest round-trip time. If a server's roundtrip time is more than LocalThreshold slower than the the fastest, the driver will not send queries to that server.
func (*ClientOptions) MaxConnIdleTime ¶ added in v0.0.3
func (co *ClientOptions) MaxConnIdleTime(d time.Duration) *ClientOptions
MaxConnIdleTime specifies the maximum number of milliseconds that a connection can remain idle in a connection pool before being removed and closed.
func (*ClientOptions) MaxConnsPerHost ¶ added in v0.0.3
func (co *ClientOptions) MaxConnsPerHost(u uint16) *ClientOptions
MaxConnsPerHost specifies the max size of a server's connection pool.
func (*ClientOptions) MaxIdleConnsPerHost ¶ added in v0.0.3
func (co *ClientOptions) MaxIdleConnsPerHost(u uint16) *ClientOptions
MaxIdleConnsPerHost specifies the number of connections in a server's connection pool that can be idle at any given time.
func (*ClientOptions) Password ¶ added in v0.0.3
func (co *ClientOptions) Password(s string) *ClientOptions
Password specifies the password used for authentication.
func (*ClientOptions) ReadConcernLevel ¶ added in v0.0.3
func (co *ClientOptions) ReadConcernLevel(s string) *ClientOptions
ReadConcernLevel specifies the read concern level of the default read concern to set on the client.
func (*ClientOptions) ReadPreference ¶ added in v0.0.3
func (co *ClientOptions) ReadPreference(s string) *ClientOptions
ReadPreference specifies the read preference mode of the default read preference to set on the client.
func (*ClientOptions) ReadPreferenceTagSets ¶ added in v0.0.3
func (co *ClientOptions) ReadPreferenceTagSets(m []map[string]string) *ClientOptions
ReadPreferenceTagSets specifies the read preference tagsets of the default read preference to set on the client.
func (*ClientOptions) ReplicaSet ¶ added in v0.0.3
func (co *ClientOptions) ReplicaSet(s string) *ClientOptions
ReplicaSet specifies the name of the replica set of the cluster.
func (*ClientOptions) SSL ¶ added in v0.0.3
func (co *ClientOptions) SSL(b bool) *ClientOptions
SSL indicates whether SSL should be enabled.
func (*ClientOptions) SSLCaFile ¶ added in v0.0.3
func (co *ClientOptions) SSLCaFile(s string) *ClientOptions
SSLCaFile specifies the file containing the certificate authority used for SSL connections.
func (*ClientOptions) SSLClientCertificateKeyFile ¶ added in v0.0.3
func (co *ClientOptions) SSLClientCertificateKeyFile(s string) *ClientOptions
SSLClientCertificateKeyFile specifies the file containing the client certificate and private key used for authentication.
func (*ClientOptions) SSLClientCertificateKeyPassword ¶ added in v0.0.3
func (co *ClientOptions) SSLClientCertificateKeyPassword(s func() string) *ClientOptions
SSLClientCertificateKeyPassword provides a callback that returns a password used for decrypting the private key of a PEM file (if one is provided).
func (*ClientOptions) SSLInsecure ¶ added in v0.0.3
func (co *ClientOptions) SSLInsecure(b bool) *ClientOptions
SSLInsecure indicates whether to skip the verification of the server certificate and hostname.
func (*ClientOptions) ServerSelectionTimeout ¶ added in v0.0.3
func (co *ClientOptions) ServerSelectionTimeout(d time.Duration) *ClientOptions
ServerSelectionTimeout specifies a timeout in milliseconds to block for server selection.
func (*ClientOptions) Single ¶ added in v0.0.3
func (co *ClientOptions) Single(b bool) *ClientOptions
Single specifies whether the driver should connect directly to the server instead of auto-discovering other servers in the cluster.
func (*ClientOptions) SocketTimeout ¶ added in v0.0.3
func (co *ClientOptions) SocketTimeout(d time.Duration) *ClientOptions
SocketTimeout specifies the time in milliseconds to attempt to send or receive on a socket before the attempt times out.
func (*ClientOptions) Username ¶ added in v0.0.3
func (co *ClientOptions) Username(s string) *ClientOptions
Username specifies the username that will be authenticated.
func (*ClientOptions) WNumber ¶ added in v0.0.3
func (co *ClientOptions) WNumber(i int) *ClientOptions
WNumber sets the "w" field of the default write concern to set on the client.
func (*ClientOptions) WString ¶ added in v0.0.3
func (co *ClientOptions) WString(s string) *ClientOptions
WString sets the "w" field of the default write concern to set on the client.
func (*ClientOptions) WTimeout ¶ added in v0.0.3
func (co *ClientOptions) WTimeout(d time.Duration) *ClientOptions
WTimeout sets the "wtimeout" field of the default write concern to set on the client.
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.AggregateOptioner) (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 *bson.Document. See TransformDocument for the list of valid types for pipeline.
func (*Collection) Count ¶
func (coll *Collection) Count(ctx context.Context, filter interface{}, opts ...options.CountOptioner) (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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) DeleteMany ¶
func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...options.DeleteOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) DeleteOne ¶
func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...options.DeleteOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) Distinct ¶
func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...options.DistinctOptioner) ([]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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) Find ¶
func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...options.FindOptioner) (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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) FindOne ¶
func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...options.FindOneOptioner) *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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) FindOneAndDelete ¶
func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...options.FindOneAndDeleteOptioner) *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 *bson.Document. See TransformDocument for the list of valid types for filter.
func (*Collection) FindOneAndReplace ¶
func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...options.FindOneAndReplaceOptioner) *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 *bson.Document. See TransformDocument for the list of valid types for filter and replacement.
func (*Collection) FindOneAndUpdate ¶
func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, opts ...options.FindOneAndUpdateOptioner) *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 *bson.Document. See TransformDocument for the list of valid types for filter and update.
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.InsertManyOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for documents.
func (*Collection) InsertOne ¶
func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...options.InsertOneOptioner) (*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 *bson.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 bson.Element or a bson.Value.
func (*Collection) ReplaceOne ¶
func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, opts ...options.ReplaceOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for filter and replacement.
func (*Collection) UpdateMany ¶
func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...options.UpdateOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for filter and update.
func (*Collection) UpdateOne ¶
func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, options ...options.UpdateOptioner) (*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 *bson.Document. See TransformDocument for the list of valid types for filter and update.
func (*Collection) Watch ¶ added in v0.0.2
func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, opts ...options.ChangeStreamOptioner) (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 ¶
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.Reader, 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 ¶
type Database struct {
// contains filtered or unexported fields
}
Database performs operations on a given database.
func (*Database) Collection ¶
func (db *Database) Collection(name string) *Collection
Collection gets a handle for a given collection in the database.
type DatabaseSpecification ¶ added in v0.0.3
DatabaseSpecification is the information for a single database returned from a ListDatabases operation.
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 DocumentResult ¶
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 ¶
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 ¶ added in v0.0.3
IndexModel contains information about an index.
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
CreateMany creates multiple indexes in the collection specified by the models. The names of the creates indexes are returned.
func (IndexView) CreateOne ¶ added in v0.0.3
CreateOne creates a single index in the collection specified by the model.
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 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 Options ¶ added in v0.0.2
type Options struct{}
Options is used as a namespace for MongoDB operation option constructors.
var Opt Options
Opt is a convenience variable provided for access to Options methods.
func (Options) AllowDiskUse ¶ added in v0.0.2
func (Options) AllowDiskUse(b bool) options.OptAllowDiskUse
AllowDiskUse enables writing to temporary files.
func (Options) AllowPartialResults ¶ added in v0.0.2
func (Options) AllowPartialResults(b bool) options.OptAllowPartialResults
AllowPartialResults gets partial results from a mongos if some shards are down (instead of throwing an error).
func (Options) ArrayFilters ¶ added in v0.0.2
func (Options) ArrayFilters(filters ...interface{}) (options.OptArrayFilters, error)
ArrayFilters specifies to which array elements an update should apply.
This function uses TransformDocument to turn the document parameter into a *bson.Document. See TransformDocument for the list of valid types for document.
func (Options) BatchSize ¶ added in v0.0.2
func (Options) BatchSize(i int32) options.OptBatchSize
BatchSize specifies the number of documents to return per batch.
func (Options) BypassDocumentValidation ¶ added in v0.0.2
func (Options) BypassDocumentValidation(b bool) options.OptBypassDocumentValidation
BypassDocumentValidation is used to opt out of document-level validation for a given write.
func (Options) Collation ¶ added in v0.0.2
func (Options) Collation(collation *options.Collation) options.OptCollation
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
func (Options) Comment ¶ added in v0.0.2
func (Options) Comment(s string) options.OptComment
Comment specifies a comment to attach to the query to help attach and trace profile data.
See https://docs.mongodb.com/manual/reference/command/profile.
func (Options) CursorType ¶ added in v0.0.2
func (Options) CursorType(cursorType options.CursorType) options.OptCursorType
CursorType indicates the type of cursor to use.
func (Options) FullDocument ¶ added in v0.0.2
func (Options) FullDocument(fullDocument string) options.OptFullDocument
FullDocument indicates which changes should be returned in a change stream notification.
If fullDocument is "updateLookup", then the change notification for partial updates will include both a delta describing the changes to the document as well as a copy of the entire document that was changed from some time after the change occurred.
func (Options) Hint ¶ added in v0.0.2
Hint specifies the index to use.
The hint parameter must be either a string or a document. If it is a document, this func (Options)tion uses TransformDocument to turn the document into a *bson.Document. See TransformDocument for the list of valid types.
func (Options) Max ¶ added in v0.0.2
Max specifies the exclusive upper bound for a specific index.
This function uses TransformDocument to turn the max parameter into a *bson.Document. See TransformDocument for the list of valid types for max.
func (Options) MaxAwaitTime ¶ added in v0.0.2
func (Options) MaxAwaitTime(duration time.Duration) options.OptMaxAwaitTime
MaxAwaitTime specifies the maximum amount of time for the server to wait on new documents to satisfy a tailable-await cursor query.
func (Options) MaxScan ¶ added in v0.0.2
func (Options) MaxScan(i int64) options.OptMaxScan
MaxScan specifies the maximum number of documents or index keys to scan when executing the query.
func (Options) MaxTime ¶ added in v0.0.2
func (Options) MaxTime(duration time.Duration) options.OptMaxTime
MaxTime specifies the maximum amount of time to allow the query to run.
func (Options) Min ¶ added in v0.0.2
Min specifies the inclusive lower bound for a specific index.
This function uses TransformDocument to turn the min parameter into a *bson.Document. See TransformDocument for the list of valid types for min.
func (Options) NoCursorTimeout ¶ added in v0.0.2
func (Options) NoCursorTimeout(b bool) options.OptNoCursorTimeout
NoCursorTimeout specifies whether to prevent the server from timing out idle cursors after an inactivity period.
func (Options) OplogReplay ¶ added in v0.0.2
func (Options) OplogReplay(b bool) options.OptOplogReplay
OplogReplay is for internal replication use only.
func (Options) Ordered ¶ added in v0.0.2
func (Options) Ordered(b bool) options.OptOrdered
Ordered specifies whether the remaining writes should be aborted if one of the earlier ones fails.
func (Options) Projection ¶ added in v0.0.2
func (Options) Projection(projection interface{}) (options.OptProjection, error)
Projection limits the fields to return for all matching documents.
This function uses TransformDocument to turn the projection parameter into a *bson.Document. See TransformDocument for the list of valid types for projection.
func (Options) ReadConcern ¶ added in v0.0.2
func (Options) ReadConcern(readConcern *readconcern.ReadConcern) (options.OptReadConcern, error)
ReadConcern for replica sets and replica set shards determines which data to return from a query.
func (Options) ResumeAfter ¶ added in v0.0.2
func (Options) ResumeAfter(token *bson.Document) options.OptResumeAfter
ResumeAfter specifies the logical starting point for a new change stream.
func (Options) ReturnDocument ¶ added in v0.0.2
func (Options) ReturnDocument(returnDocument options.ReturnDocument) options.OptReturnDocument
ReturnDocument specifies whether a findAndUpdate should return the document as it was before the update or as it is after.
func (Options) ReturnKey ¶ added in v0.0.2
func (Options) ReturnKey(b bool) options.OptReturnKey
ReturnKey specifies whether to only return the index keys in the resulting documents.
func (Options) ShowRecordID ¶ added in v0.0.2
func (Options) ShowRecordID(b bool) options.OptShowRecordID
ShowRecordID determines whether to return the record identifier for each document.
func (Options) Skip ¶ added in v0.0.2
Skip specifies the number of documents to skip before returning.
func (Options) Snapshot ¶ added in v0.0.2
func (Options) Snapshot(b bool) options.OptSnapshot
Snapshot specifies whether to prevent the cursor from returning a document more than once because of an intervening write operation.
func (Options) Sort ¶ added in v0.0.2
Sort specifies order in which to return matching documents.
This function uses TransformDocument to turn the sort parameter into a *bson.Document. See TransformDocument for the list of valid types for sort.
func (Options) Upsert ¶ added in v0.0.2
Upsert specifies that a new document should be inserted if no document matches the update filter.
func (Options) WriteConcern ¶ added in v0.0.2
func (Options) WriteConcern(writeConcern *writeconcern.WriteConcern) (options.OptWriteConcern, error)
WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters.
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 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.