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
- 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{}, options ...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{}, options ...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) 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 DeleteResult
- type DocumentResult
- type InsertManyResult
- type InsertOneResult
- 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 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 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.
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 cluster.
func NewClientFromConnString ¶
func NewClientFromConnString(cs connstring.ConnString) (*Client, error)
NewClientFromConnString creates a new client to connect to a cluster specified by the connection string.
func (*Client) ConnectionString ¶
ConnectionString returns the connection string of the cluster the client is connected to.
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{}, options ...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{}, options ...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{}, options ...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) 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 DeleteResult ¶
type DeleteResult struct { // The number of documents that were deleted. DeletedCount int64 `bson:"n"` }
DeleteResult is a result of an DeleteOne operation.
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 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 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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package private and all packages underneath it are not for public use.
|
Package private and all packages underneath it are not for public use. |
auth
Package auth is not for public use.
|
Package auth is not for public use. |
cluster
Package cluster is not for public use.
|
Package cluster is not for public use. |
conn
Package conn is not for public use.
|
Package conn is not for public use. |
msg
Package msg is not for public use.
|
Package msg is not for public use. |
ops
Package ops is not for public use.
|
Package ops is not for public use. |
server
Package server is not for public use.
|
Package server is not for public use. |