mongo

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2018 License: Apache-2.0 Imports: 17 Imported by: 19,494

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.C.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

Constants

This section is empty.

Variables

View Source
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 AllowDiskUse

func AllowDiskUse(b bool) options.OptAllowDiskUse

AllowDiskUse enables writing to temporary files.

func AllowPartialResults

func AllowPartialResults(b bool) options.OptAllowPartialResults

AllowPartialResults gets partial results from a mongos if some shards are down (instead of throwing an error).

func ArrayFilters

func 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 BatchSize

func BatchSize(i int32) options.OptBatchSize

BatchSize specifies the number of documents to return per batch.

func BypassDocumentValidation

func BypassDocumentValidation(b bool) options.OptBypassDocumentValidation

BypassDocumentValidation is used to opt out of document-level validation for a given write.

func Collation

func Collation(collation *options.CollationOptions) options.OptCollation

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

See https://docs.mongodb.com/manual/reference/collation/.

func Comment

func 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 CursorType

func CursorType(cursorType options.CursorType) options.OptCursorType

CursorType indicates the type of cursor to use.

func Hint

func Hint(hint interface{}) (options.OptHint, error)

Hint specifies the index to use.

The hint parameter must be either a string or a document. If it is a document, this function uses TransformDocument to turn the document into a *bson.Document. See TransformDocument for the list of valid types.

func Limit

func Limit(i int64) options.OptLimit

Limit specifies the maximum number of documents to return.

func Max

func Max(max interface{}) (options.OptMax, error)

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 MaxAwaitTime

func 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 MaxScan

func MaxScan(i int64) options.OptMaxScan

MaxScan specifies the maximum number of documents or index keys to scan when executing the query.

func MaxTime

func MaxTime(duration time.Duration) options.OptMaxTime

MaxTime specifies the maximum amount of time to allow the query to run.

func Min

func Min(min interface{}) (options.OptMin, error)

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 NoCursorTimeout

func NoCursorTimeout(b bool) options.OptNoCursorTimeout

NoCursorTimeout specifies whether to prevent the server from timing out idle cursors after an inactivity period.

func OplogReplay

func OplogReplay(b bool) options.OptOplogReplay

OplogReplay is for internal replication use only.

func Ordered

func Ordered(b bool) options.OptOrdered

Ordered specifies whether the remaining writes should be aborted if one of the earlier ones fails.

func Projection

func 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 ReturnDocument

func 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 ReturnKey

func ReturnKey(b bool) options.OptReturnKey

ReturnKey specifies whether to only return the index keys in the resulting documents.

func ShowRecordID

func ShowRecordID(b bool) options.OptShowRecordID

ShowRecordID determines whether to return the record identifier for each document.

func Skip

func Skip(i int64) options.OptSkip

Skip specifies the number of documents to skip before returning.

func Snapshot

func 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 Sort

func Sort(sort interface{}) (options.OptSort, error)

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 TransformDocument

func TransformDocument(document interface{}) (*bson.Document, error)

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

func Upsert

func Upsert(b bool) options.OptUpsert

Upsert specifies that a new document should be inserted if no document matches the update filter.

Types

type Client

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

Client performs operations on a given cluster.

func NewClient

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

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

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

func (client *Client) ConnectionString() string

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

func (*Client) Database

func (client *Client) Database(name string) *Database

Database returns a handle for a given database.

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{},
	options ...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{},
	options ...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{},
	options ...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{},
	options ...options.FindOptioner) *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{},
	options ...options.InsertOptioner) (*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{},
	options ...options.InsertOptioner) (*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{},
	options ...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.

type Cursor

type Cursor ops.Cursor

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:

cursor := ...    // get a cursor from some operation
ctx := ...       // create a context for the operation
var doc bson.D
for cursor.Next(ctx, &doc) {
	...
}
err := cursor.Close(ctx)

type Database

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

Database performs operations on a given database.

func (*Database) Client

func (db *Database) Client() *Client

Client returns the Client the database was created from.

func (*Database) Collection

func (db *Database) Collection(name string) *Collection

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

func (*Database) Name

func (db *Database) Name() string

Name returns the name of the database.

func (*Database) RunCommand

func (db *Database) RunCommand(ctx context.Context, command interface{}) (bson.Reader, 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().

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

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.

Jump to

Keyboard shortcuts

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