import "github.com/garyburd/go-mongo/mongo"
Package mongo is a driver for MongoDB.
The core interface to MongoDB is defined by the Conn interface. This interface provides access to all MongoDB functionality, but it is is not always convenient to use for common tasks.
The Database, Collection and Query types provide a number of convenience methods for working with Conn objects.
Conn objects are not thread-safe. Multi-threaded applications are responsible for serializing access to Conn objects.
Code:play
package mongo_test
import (
"github.com/garyburd/go-mongo/mongo"
"log"
)
type ExampleDoc struct {
Id mongo.ObjectId `bson:"_id"`
Title string
Body string
}
func Example() {
// Connect to server.
conn, err := mongo.Dial("localhost")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
c := mongo.Collection{conn, "example-db.example-collection", mongo.DefaultLastErrorCmd}
// Insert a document.
id := mongo.NewObjectId()
err = c.Insert(&ExampleDoc{Id: id, Title: "Hello", Body: "Mongo is fun."})
if err != nil {
log.Fatal(err)
}
// Find the document.
var doc ExampleDoc
err = c.Find(map[string]interface{}{"_id": id}).One(&doc)
if err != nil {
log.Fatal(err)
}
log.Print(doc.Title, " ", doc.Body)
}
var DefaultLastErrorCmd interface{} = map[string]int{"getLastError": 1}var Done = errors.New("mongo: cursor has no more results")Cursor has no more results.
var ErrEOD = errors.New("bson: unexpected end of data when parsing BSON")var ErrNotFound = errors.New("mongo: not found")
func Decode(data []byte, v interface{}) (err error)Deocde decodes BSON data to value v.
Decode traverses the value v recursively. Decode uses the inverse of the encodings supported by Encode, allocating maps, slices and pointers as needed. The following conversions from BSON types to GO types are supported:
BSON -> Go
Integer32 -> signed and unsigned integers, floats, bool
Integer64 -> signed and unsigned integers, floats, bool
Array -> []interface{}, other slice types
Binary -> []byte
Boolean -> bool
Datetime -> time.Time, int64
Document -> map[string]interface{}, struct types
Double -> signed and unsigned integers, floats, bool
MinValue, MaxValue -> mongo.MinMax
ObjectID -> mongo.ObjectId
Symbol -> mongo.Symbol, string
Timestamp -> mongo.Timestamp, int64
string -> string
If a number overflows the target type or the BSON value cannot be converted to the target type, then the decoding completes the best it can and an error is returned.
To decode a BSON value into a nil interface value, the first type listed in the right hand column of the table above is used.
func Encode(buf []byte, doc interface{}) (result []byte, err error)Encode appends the BSON encoding of doc to buf and returns the new slice.
Encode traverses the value doc recursively using the following type-dependent encodings:
Struct values encode as BSON documents. Each exported struct field is written as a document element subject to comma separated options in the "bson" struct field tag. The first option specifies the name of the document element. If the name is "-", then the field is ignored. If the name is "", then the name of the struct field is used as the name of the document element. The remaining options are:
omitempty If the field is the zero value, then the field is not
written to the encoding.
Anonymous struct fields are encoded in-line with the containing struct.
Array and slice values encode as BSON arrays.
Map values encode as BSON documents. The map's key type must be string; the object keys are used directly as map keys.
Pointer values encode as the value pointed to.
Interface values encode as the value contained in the interface.
Other types are encoded as follows
Go -> BSON bool -> Boolean float32 -> Double float64 -> Double int, uint, uint32 -> Integer32 if value fits in int32, else Integer64 int8, int16, int32 -> Integer32 uint8, uint16 -> Integer32 int64, uint64 -> Integer64 string -> String []byte -> Binary data time.Time -> UTC Datetime mongo.Code -> Javascript code mongo.CodeWithScope -> Javascript code with scope mongo.D -> Document. Use when element order is important. mongo.MinMax -> Minimum / Maximum value mongo.ObjectId -> ObjectId mongo.Regexp -> Regular expression mongo.Symbol -> Symbol mongo.Timestamp -> Timestamp
Other types including channels, complex and function values cannot be encoded.
BSON cannot represent cyclic data structure and Encode does not handle them. Passing cyclic structures to Encode will result in an infinite recursion.
func IndexName(keys D) string
IndexName returns the standard name for an index with keys.
func SplitNamespace(s string) (string, string)
SplitNamespace splits a namespace into database name and collection name components.
func StructFields(t reflect.Type) interface{}
StructFields returns a MongoDB field specification for the given struct type.
type A []interface{}A is a shortcut for writing []interface{} in BSON literal expressions. The type A is encoded the same as the type []interface{}.
type BSONData struct {
Kind int
Data []byte
}BSONData represents a chunk of uninterpreted BSON data. Use this type to copy raw data into or out of a BSON encoding.
func (bd BSONData) Decode(v interface{}) error
Deocde decodes bd to v. See the Decode function for more information about BSON decoding.
type Code string
Code represents Javascript code in BSON.
type CodeWithScope struct {
Code string
Scope map[string]interface{}
}CodeWithScope represents javascript in BSON.
type Collection struct {
// Connection to the database.
Conn Conn
// String with the format "<database>.<collection>" where <database> is the
// name of the database and <collection> is the name of the collection.
Namespace string
// Command used to check for errors after on insert, update or remove
// operation on the collection. If nil, then errors are not checked.
LastErrorCmd interface{}
}Collection represents a MongoDB collection.
func (c Collection) CreateIndex(keys D, options *IndexOptions) error
CreateIndex creates an index on keys.
More information: http://www.mongodb.org/display/DOCS/Indexes
func (c Collection) Db() Database
Db returns the database for this collection.
func (c Collection) Find(filter interface{}) *Query
Find returns a query object for the given filter.
func (c Collection) Insert(documents ...interface{}) error
Insert adds document to the collection.
func (c Collection) Name() string
Name returns the collection's name.
func (c Collection) Remove(selector interface{}) error
Remove removes all documents found by selector.
func (c Collection) RemoveFirst(selector interface{}) error
RemoveFirst removes the first document found by selector.
func (c Collection) Update(selector, update interface{}) error
Update updates the first document in the collection found by selector with update. If a matching document is not found, then mongo.ErrNotFound is returned.
func (c Collection) UpdateAll(selector interface{}, update interface{}) error
UpdateAll updates all documents matching selector with update. If no matching documents are found, then mongo.ErrNotFound is returned.
func (c Collection) Upsert(selector interface{}, update interface{}) error
Upsert updates the first document found by selector with update. If no document is found, then the update is inserted instead.
type CommandResponse struct {
Ok bool `bson:"ok"`
Errmsg string `bson:"errmsg"`
}CommandResponse contains the common fields in command responses from the server.
func (s CommandResponse) Err() error
Error returns the error from the response or nil.
type Conn interface {
// Close releases the resources used by this connection.
Close() error
// Error returns non-nil if the connection has a permanent error.
Err() error
// Update document specified by selector with update.
Update(namespace string, selector, update interface{}, options *UpdateOptions) error
// Insert documents.
Insert(namespace string, options *InsertOptions, documents ...interface{}) error
// Remove documents specified by selector.
Remove(namespace string, selector interface{}, options *RemoveOptions) error
// Find documents specified by selector. The returned cursor must be closed.
Find(namespace string, query interface{}, options *FindOptions) (Cursor, error)
}A Conn represents a connection to a MongoDB server.
When the application is done using the connection, the application must call the connection Close() method to release the resources used by the connection.
The methods in this interface use a namespace string to specify the database and collection. A namespace string has the format "<database>.<collection>" where <database> is the name of the database and <collection> is the name of the collection.
func Dial(addr string) (Conn, error)
Dial connects to server at addr.
func NewLoggingConn(conn Conn, log *log.Logger, prefix string) Conn
NewLoggingConn returns a logging wrapper around a connection.
type Cursor interface {
// Close releases the resources used by this connection.
Close() error
// Err returns non-nil if the cursor has a permanent error.
Err() error
// HasNext returns true if there are more documents to retrieve.
HasNext() bool
// Next fetches the next document from the cursor. Value must be a map or
// a non-nil pointer to struct or map.
Next(value interface{}) error
}Cursor iterates over the results from a Find operation.
When the application is done using a cursor, the application must call the cursor Close() method to release the resources used by the cursor.
An example use of a cursor is:
cursor, err := c.Find("db.coll", mongo.Doc{}, nil)
if err != nil {
return err
}
defer cursor.Close()
for cursor.HasNext() {
var m map[string]interface{}
err = r.Next(&m)
if err != nil {
return err
}
// Do something with result document m.
}
Tailable cursors are supported. When working with a tailable cursor, use the expression cursor.Err() != nil to determine if the cursor is "dead." See http://www.mongodb.org/display/DOCS/Tailable+Cursors for more discussion on tailable cursors.
type D []DocItem
D represents an ordered BSON document. Use D for commands, index specifications and other situations where the order of the key-value pairs in a document is important.
func (d *D) Append(name string, value interface{})
Append adds an item to the document..
type DBRef struct {
// The target document's collection.
Collection string `bson:"$ref"`
// The target document's id.
Id ObjectId `bson:"$id"`
// The target document's database (optional).
Database string `bson:"$db,omitempty"`
}DBRef is a reference to a document in a database. Use the Database Dereference method to get the referenced document.
More information: http://www.mongodb.org/display/DOCS/Database+References
type Database struct {
// Connection to the database.
Conn Conn
// Database name.
Name string
// Command used to check for errors after on insert, update or remove
// operation on the collection. If nil, then errors are not checked.
LastErrorCmd interface{}
}Database represents a MongoDb database.
func (db Database) AddUser(name, password string, readOnly bool) error
AddUser creates a user with name and password. If the user already exists, then the password is updated.
func (db Database) Authenticate(name, password string) error
Authenticate authenticates user with name and password to this database.
func (db Database) C(name string) Collection
C returns the collection with name. This is a lightweight operation. The method does not check to see if the collection exists in the database.
func (db Database) Dereference(ref DBRef, slaveOk bool, result interface{}) error
Deference fetches the document specified by a database reference.
func (db Database) LastError(cmd interface{}) (*MongoError, error)
LastError returns the last error for the database using cmd. If cmd is nil, then the command {"getLasetError": 1} is used to get the error.
More information: http://www.mongodb.org/display/DOCS/Last+Error+Commands
func (db Database) RemoveUser(name string) error
RemoveUser removes user with name from the database.
func (db Database) Run(cmd interface{}, result interface{}) error
Run runs the command cmd on the database.
More information: http://www.mongodb.org/display/DOCS/Commands
type DecodeConvertError struct {
// contains filtered or unexported fields
}DecodeConvertError is returned when decoder cannot convert BSON value to the target type.
func (e *DecodeConvertError) Error() string
type DecodeTypeError struct {
// contains filtered or unexported fields
}DecodeTypeError is returned when the decoder encounters an unknown type in the input.
func (e *DecodeTypeError) Error() string
type DocItem struct {
Key string
Value interface{}
}
type EncodeTypeError struct {
Type reflect.Type
}EncodeTypeError is the error indicating that Encode could not encode an input type.
func (e *EncodeTypeError) Error() string
type FindOptions struct {
// Optional document that limits the fields in the returned documents.
// Fields contains one or more elements, each of which is the name of a
// field that should be returned, and the integer value 1.
Fields interface{}
// Do not close the cursor when no more data is available on the server.
Tailable bool
// Allow query of replica slave.
SlaveOk bool
// Do not close the cursor on the server after a period of inactivity (10
// minutes).
NoCursorTimeout bool
// Block at server for a short time if there's no data for a tailable cursor.
AwaitData bool
// Stream the data down from the server full blast. Normally the server
// waits for a "get more" message before sending a batch of data to the
// client. With this option set, the server sends batches of data without
// waiting for the "get more" messages.
Exhaust bool
// Allow partial results in sharded environment. Normally the query
// will fail if a shard is not available.
PartialResults bool
// Skip specifies the number of documents the server should skip at the
// beginning of the result set.
Skip int
// Sets the number of documents to return.
Limit int
// Sets the batch size used for sending documents from the server to the
// client.
BatchSize int
}FindOptions specifies options for the Conn.Find method.
type IndexOptions struct {
// Custom name for this index. If none specified, then a name will be generated.
Name string `bson:"name"`
// Should this index guarantee uniqueness?
Unique bool `bson:"unique,omitempty"`
// Should duplicates be dropped when creating a unique index?
DropDups bool `bson:"dropDups,omitempty"`
// Build index in background.
Background bool `bson:"background,omitempty"`
// Do not index documents with missing key fields.
Sparse bool `bson:"sparse,omitempty"`
// Geospatial options
Min interface{} `bson:"min"`
Max interface{} `bson:"max"`
Bits int `bson:"bits,omitempty"`
}IndexOptions specifies options for the collection CreateIndex method.
More information: http://www.mongodb.org/display/DOCS/Indexes
type InsertOptions struct {
// If true, the server will not stop processing a bulk insert if one insert fails.
ContinueOnError bool
}InsertOptions specifies options for the Conn.Insert method.
type M map[string]interface{}M is a shortcut for writing map[string]interface{} in BSON literal expressions. The type M is encoded the same as the type map[string]interface{}.
type MinMax int
MinMax represents either a minimum or maximum BSON value.
const (
// MaxValue is the maximum BSON value.
MaxValue MinMax = 1
// MinValue is the minimum BSON value.
MinValue MinMax = -1
)
type MongoError struct {
Err string `bson:"err"`
N int `bson:"n"`
Code int `bson:"code"`
Updated bool `bson:"updatedExisting"`
UpsertedId interface{} `bson:"upserted"`
}MongoError represents an error for the connection mutation operations.
func (e *MongoError) Error() string
type ObjectId string
ObjectId represents a BSON object identifier.
func MaxObjectIdForTime(t time.Time) ObjectId
MaxObjectIdForTime returns the maximum object id for time t in seconds from the epoch.
func MinObjectIdForTime(t time.Time) ObjectId
MinObjectIdForTime returns the minimum object id for time t in seconds from the epoch.
func NewObjectId() ObjectId
NewObjectId returns a new object id. This function uses the following format for object ids:
[0:4] Big endian time since epoch in seconds. This is compatible
with other drivers.
[4:12] Incrementing counter initialized with cryptographic random number.
This ensures that object ids are unique, but is simpler than
the format used by other drivers.
func NewObjectIdHex(hexString string) (ObjectId, error)
NewObjectIdHex returns an object id initialized from the hexadecimal encoding of the object id.
func (id ObjectId) CreationTime() time.Time
CreationTime extracts the time the object id was created in seconds since the epoch.
func (id ObjectId) MarshalJSON() ([]byte, error)
MarshalJSON returns the JSON encoding of id.
func (id ObjectId) String() string
String returns the hexadecimal encoding of id. Use the function NewObjectIdHex to convert the string back to an object id.
func (id *ObjectId) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes id from JSON to ObjectId.
type Pool struct {
// contains filtered or unexported fields
}Pool maintains a pool of database connections.
The following example shows how to use a pool in a web application. The application creates a pool at application startup and makes it available to request handlers, possibly using a global variable:
var server string // host:port of server
var name, password string // authentication credentials
...
pool = mongo.NewPool(func () (c mongo.Conn, err os.Error) {
c, err = mongo.Dial(server)
if err != nil {
return
}
err = mongo.Database{c, "admin", nil}.Authenticate(name, password)
if err != nil {
c.Close()
c = nil
}
return
}, 3)
This pool has a maximum of three connections to the server specified by the variable "server". Each connection is logged into the "admin" database using the credentials specified by the variables "name" and "password".
A request handler gets a connection from the pool and closes the connection when the handler is done:
conn, err := pool.Get()
if err != nil {
// handle the error
}
defer conn.Close()
// do something with the connection
Close() returns the connection to the pool if there's room in the pool and the connection does not have a permanent error. Otherwise, Close() releases the resources used by the connection.
func NewDialPool(addr string, maxIdle int) *Pool
NewDialPool returns a new connection pool. The pool uses mongo.Dial to create new connections and maintains a maximum of maxIdle connections.
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool
NewPool returns a new connection pool. The pool uses newFn to create connections as needed and maintains a maximum of maxIdle idle connections.
func (p *Pool) Get() (Conn, error)
Get returns an idle connection from the pool if available or creates a new connection. The caller should Close() the connection to return the connection to the pool.
type Query struct {
Conn Conn
Namespace string
Spec QuerySpec
Options FindOptions
}Query represents a query to the database.
func (q *Query) All(slicep interface{}) error
All executes the query and returns the entire result set in *slicep. The slicep argument must be a pointer to a slice and the elements of the slice must be valid document types.
func (q *Query) BatchSize(batchSize int) *Query
BatchSize sets the batch sized used for sending documents from the server to the client.
func (q *Query) Count() (int64, error)
Count returns the number of documents that match the query. Limit and skip are considered in the count.
func (q *Query) Cursor() (Cursor, error)
Cursor executes the query and returns a cursor over the results. Subsequent changes to the query object are ignored by the cursor.
func (q *Query) Distinct(key interface{}, result interface{}) error
Distinct returns the distinct value for key among the documents in the result set for this query.
More information: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
func (q *Query) Exhaust(exhaust bool) *Query
Exhaust specifies if the server should stream data to the client full blast. Normally the server waits for a "get more" message before sending a batch of data to the client. With this option set, the server sends batches of data without waiting for the "get more" messages.
func (q *Query) Explain(result interface{}) error
Explain returns an explanation of how the server will execute the query.
More information: http://www.mongodb.org/display/DOCS/Optimization#Optimization-Explain
func (q *Query) Fields(fields interface{}) *Query
Fields limits the fields in the returned documents. Fields contains one or more elements, each of which is the name of a field that should be returned, and the integer value 1.
More information: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields
func (q *Query) Fill(slice interface{}) (n int, err error)
Fill executes the query and copies up to len(slice) documents to slice. The elements of slice must be valid document types (struct, map with string key) or pointers to valid document types. The function returns the number of documents in the result set.
func (q *Query) Hint(hint interface{}) *Query
Hint specifies an index hint. The index is specified by (key, direction) pairs. Direction is 1 for ascending order and -1 for descending order.
More information: http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint
func (q *Query) Limit(limit int) *Query
Limit specifies the number of documents to return from the query.
More information: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D
func (q *Query) One(output interface{}) error
One executes the query and returns the first result.
func (q *Query) PartialResults(ok bool) *Query
PartialResults specifies if mongos can reply with partial results when a shard is missing.
func (q *Query) Remove(result interface{}) error
Remove returns the first document matching the query after removing the document from the database. Use the Sort method to specify the sort order for matching the documents and the Fields method to specify the returned fields.
Remove is a wrapper around the MongoDB findAndModify command.
func (q *Query) Skip(skip int) *Query
Skip specifies the number of documents the server should skip at the beginning of the result set.
More information: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D
func (q *Query) SlaveOk(slaveOk bool) *Query
SlaveOk specifies if query can be routed to a slave.
More information: http://www.mongodb.org/display/DOCS/Querying#Querying-slaveOk
func (q *Query) Sort(sort interface{}) *Query
Sort specifies the sort order for the result. The order is specified by (key, direction) pairs. Direction is 1 for ascending order and -1 for descending order.
func (q *Query) Tailable(tailable bool) *Query
Tailable specifies if the server should not close the cursor when no more data is available.
More information: http://www.mongodb.org/display/DOCS/Tailable+Cursors
func (q *Query) Update(update interface{}, modified bool, result interface{}) error
Update updates the first document matching the query. The modified document is returned if modified is true, otherwise the original document is returned. Use the Sort method to specify the sort order for matching the documents and the Fields method to specify the returned fields.
Update is a wrapper around the MongoDB findAndModify command.
func (q *Query) Upsert(update interface{}, modified bool, result interface{}) error
Upsert updates the first document matching the query. If a matching document is not found, then the update is inserted instead. The modified document is returned if modified is true, otherwise the original document is returned. Use the Sort method to specify the sort order for matching the documents and the Fields method to specify the returned fields.
Upsert is a wrapper around the MongoDB findAndModify command.
type QuerySpec struct {
// The filter. This field is required.
Query interface{} `bson:"$query"`
// Sort order specified by (key, direction) pairs. The direction is 1 for
// ascending order and -1 for descending order.
Sort interface{} `bson:"$orderby"`
// If set to true, then the query returns an explain plan record the query.
// See http://www.mongodb.org/display/DOCS/Optimization#Optimization-Explain
Explain bool `bson:"$explain,omitempty"`
// Index hint specified by (key, direction) pairs.
// See http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint
Hint interface{} `bson:"$hint"`
// Snapshot mode assures that objects which update during the lifetime of a
// query are returned once and only once.
// See http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database
Snapshot bool `bson:"$snapshot,omitempty"`
// Min and Max constrain matches to those having index keys between the min
// and max keys specified.The Min value is included in the range and the
// Max value is excluded.
// See http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers
Min interface{} `bson:"$min"`
Max interface{} `bson:"$max"`
}QuerySpec is a helper for specifying complex queries.
type Regexp struct {
Pattern string
// The valid options are:
// i Case insensitive matching
// l Make \w, \W, etc. locale-dependent
// m Multi-line matching
// s Dotall mode
// u Make \w, \W, etc. match Unicode
// x Verbose mode
// Options must be specified in alphabetical order.
Options string
}Regexp represents a BSON regular expression.
type RemoveOptions struct {
// If true, then the database removes the first matching document in the
// collection. Otherwise all matching documents are removed.
Single bool
}RemoveOptions specifies options for the Conn.Remove method.
type Symbol string
Symbol represents a BSON symbol.
type Timestamp int64
Timestamp represents a BSON timesamp.
type UpdateOptions struct {
// If true, then the database inserts the supplied object into the
// collection if no matching document is found.
Upsert bool
// If true, then the database updates all objects matching the query.
Multi bool
}UpdateOptions specifies options for the Conn.Update method.
bson_decode.go mongo.go pool.go query.go log.go connection.go buffer.go bson.go database.go bson_encode.go collection.go