mgo

package module
v0.0.0-...-3003033 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2021 License: Apache-2.0 Imports: 21 Imported by: 0

README

mgo

Use mongo-go-driver like mgo

installation

go get -u github.com/yaziming/mgo

usage

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrIndexNotFound = errors.New("index not found")
)
View Source
var (
	// ErrNotFound multierror returned when a document could not be found
	ErrNotFound = mongo.ErrNoDocuments
)

Functions

func IsDup

func IsDup(err error) bool

func ShouldErrorMatche

func ShouldErrorMatche(actual interface{}, params ...interface{}) string

func ShouldMatch

func ShouldMatch(actual interface{}, params ...interface{}) string

Types

type BuildInfo

type BuildInfo struct {
	Version        string
	VersionArray   []int  `bson:"versionArray"` // On MongoDB 2.0+; assembled from Version otherwise
	GitVersion     string `bson:"gitVersion"`
	OpenSSLVersion string `bson:"OpenSSLVersion"`
	Bits           int
	Debug          bool
	MaxObjectSize  int `bson:"maxBsonObjectSize"`
}

type Bulk

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

func (*Bulk) Insert

func (b *Bulk) Insert(docs ...interface{})

func (*Bulk) Remove

func (b *Bulk) Remove(selectors ...interface{})

func (*Bulk) RemoveAll

func (b *Bulk) RemoveAll(selectors ...interface{})

func (*Bulk) Run

func (b *Bulk) Run(others ...*options.BulkWriteOptions) (br *BulkResult, bulkerr error)

func (*Bulk) Unordered

func (b *Bulk) Unordered()

func (*Bulk) Update

func (b *Bulk) Update(pairs ...interface{})

func (*Bulk) UpdateAll

func (b *Bulk) UpdateAll(pairs ...interface{})

func (*Bulk) Upsert

func (b *Bulk) Upsert(pairs ...interface{})

type BulkError

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

BulkError holds an error returned from running a Bulk operation. Individual errors may be obtained and inspected via the Cases method.

func (*BulkError) Cases

func (e *BulkError) Cases() []BulkErrorCase

func (*BulkError) Error

func (e *BulkError) Error() string

type BulkErrorCase

type BulkErrorCase struct {
	Index int // Position of operation that failed, or -1 if unknown.
	Err   error
}

type BulkResult

type BulkResult struct {
	Matched   int
	Modified  int // Available only for MongoDB 2.6+
	Inserted  int
	UpsertIds map[int64]interface{}
	Deleted   int
	Upserted  int
}

BulkResult holds the results for a bulk operation.

type Change

type Change struct {
	Update    interface{} // The update document
	Upsert    bool        // Whether to insert in case the document isn't found
	Remove    bool        // Whether to remove the document found rather than updating
	ReturnNew bool        // Should the modified document be returned rather than the old one
}

type ChangeInfo

type ChangeInfo struct {
	// Updated reports the number of existing documents modified.
	// Due to server limitations, this reports the same value as the Matched field when
	// talking to MongoDB <= 2.4 and on Upsert and Apply (findAndModify) operations.
	Updated    int
	Removed    int         // Number of documents removed
	Matched    int         // Number of documents matched but not necessarily changed
	UpsertedId interface{} // Upserted _id field, when not explicitly provided
}

type Collation

type Collation = options.Collation

type Collection

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

Collection session-driver coll

func (*Collection) Bulk

func (c *Collection) Bulk() *Bulk

func (*Collection) Count

func (c *Collection) Count() (count int, err error)

func (*Collection) CountBy

func (c *Collection) CountBy(selector interface{}) (count int, err error)

Count gets the number of documents matching the filter.

func (*Collection) Create

func (c *Collection) Create(info *CollectionInfo) error

func (*Collection) Database

func (c *Collection) Database() *Database

func (*Collection) DropAllIndexes

func (c *Collection) DropAllIndexes() (err error)

func (*Collection) DropCollection

func (c *Collection) DropCollection() error

func (*Collection) DropIndex

func (c *Collection) DropIndex(key ...string) (err error)

func (*Collection) DropIndexName

func (c *Collection) DropIndexName(name string) error

func (*Collection) EnsureIndex

func (c *Collection) EnsureIndex(index Index) (err error)

func (*Collection) EnsureIndexKey

func (c *Collection) EnsureIndexKey(key ...string) (err error)

func (*Collection) Find

func (c *Collection) Find(filter interface{}) *Query

Find finds docs by given filter

func (*Collection) FindId

func (c *Collection) FindId(id interface{}) *Query

UpdateID updates a single document in the coll by id

func (*Collection) Indexes

func (c *Collection) Indexes() (indexes []Index, err error)

func (*Collection) Insert

func (c *Collection) Insert(documents ...interface{}) (err error)

Insert inserts a single document into the coll.

func (*Collection) InsertCtx

func (c *Collection) InsertCtx(ctx context.Context, documents ...interface{}) (err error)

func (*Collection) InsertCtxWithResult

func (c *Collection) InsertCtxWithResult(ctx context.Context, documents ...interface{}) (result *mongo.InsertManyResult, err error)

InsertAllWithResult inserts the provided documents and returns insert many result.

func (*Collection) Pipe

func (c *Collection) Pipe(pipeline interface{}) *Pipe

func (*Collection) Remove

func (c *Collection) Remove(selector interface{}) (err error)

Remove deletes a single document from the coll.

func (*Collection) RemoveAll

func (c *Collection) RemoveAll(selector interface{}) (info *ChangeInfo, err error)

RemoveAll deletes multiple documents from the coll.

func (*Collection) RemoveId

func (c *Collection) RemoveId(id interface{}) error

func (*Collection) ReplaceOneCtx

func (c *Collection) ReplaceOneCtx(ctx context.Context, selector interface{}, update interface{}, upsert ...bool) (err error)

func (*Collection) ReplaceOneCtxWithResult

func (c *Collection) ReplaceOneCtxWithResult(ctx context.Context, selector interface{}, update interface{}, upsert ...bool) (result *mongo.UpdateResult, err error)

func (*Collection) Update

func (c *Collection) Update(selector interface{}, update interface{}) (err error)

func (*Collection) UpdateAll

func (c *Collection) UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error)

func (*Collection) UpdateAllCtx

func (c *Collection) UpdateAllCtx(ctx context.Context, selector interface{}, update interface{}) (info *ChangeInfo, err error)

func (*Collection) UpdateAllCtxWithResult

func (c *Collection) UpdateAllCtxWithResult(ctx context.Context, selector interface{}, update interface{}, upsert ...bool) (*mongo.UpdateResult, error)

UpdateAll updates multiple documents in the coll.

func (*Collection) UpdateId

func (c *Collection) UpdateId(id interface{}, update interface{}) error

UpdateID updates a single document in the coll by id

func (*Collection) UpdateOneCtx

func (c *Collection) UpdateOneCtx(ctx context.Context, selector interface{}, update interface{}, upsert ...bool) (err error)

Update updates a single document in the coll.

func (*Collection) UpdateOneCtxWithResult

func (c *Collection) UpdateOneCtxWithResult(ctx context.Context, selector interface{}, update interface{}, upsert ...bool) (result *mongo.UpdateResult, err error)

UpdateOneCtxWithResult updates a single document in the coll and returns update result.

func (*Collection) Upsert

func (c *Collection) Upsert(selector interface{}, update interface{}) (info *ChangeInfo, err error)

func (*Collection) UpsertId

func (c *Collection) UpsertId(i interface{}, doc bson.M) (*ChangeInfo, error)

type CollectionInfo

type CollectionInfo struct {

	// ForceIdIndex enforces the automatic creation of the index
	// on the _id field for the coll. Capped collections,
	// for example, do not have such an index by default.
	ForceIdIndex bool

	// If Capped is true new documents will replace old ones when
	// the coll is full. MaxBytes must necessarily be set
	// to define the size when the coll wraps around.
	// MaxDocs optionally defines the number of documents when it
	// wraps, but MaxBytes still needs to be set.
	Capped   bool
	MaxBytes int
	MaxDocs  int

	// Validator contains a validation expression that defines which
	// documents should be considered valid for this coll.
	Validator interface{}

	// ValidationLevel may be set to "strict" (the default) to force
	// MongoDB to validate all documents on inserts and updates, to
	// "moderate" to apply the validation rules only to documents
	// that already fulfill the validation criteria, or to "off" for
	// disabling validation entirely.
	ValidationLevel string

	// ValidationAction determines how MongoDB handles documents that
	// violate the validation rules. It may be set to "error" (the default)
	// to reject inserts or updates that violate the rules, or to "warn"
	// to log invalid operations but allow them to proceed.
	ValidationAction string

	// StorageEngine allows specifying coll options for the
	// storage engine in use. The map keys must hold the storage engine
	// name for which options are being specified.
	StorageEngine interface{}
	// Specifies the default collation for the coll.
	// Collation allows users to specify language-specific rules for string
	// comparison, such as rules for lettercase and accent marks.
	Collation *Collation
}

type Database

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

Database session-driver db

func (*Database) C

func (d *Database) C(collection string) *Collection

C returns coll.

func (*Database) Close

func (d *Database) Close()

func (*Database) CollectionNames

func (d *Database) CollectionNames() ([]string, error)

func (*Database) DropDatabase

func (d *Database) DropDatabase() error

func (*Database) GridFS

func (d *Database) GridFS(prefix string) *GridFS

func (*Database) Run

func (d *Database) Run(cmd interface{}, t interface{}) error

func (*Database) Version

func (d *Database) Version() *semver.Version

type DialInfo

type DialInfo struct {
	// Addrs holds the addresses for the seed servers.
	Addrs []string

	// Timeout is the amount of time to wait for a server to respond when
	// first connecting and on follow up operations in the session. If
	// timeout is zero, the call may block forever waiting for a connection
	// to be established. Timeout does not affect logic in DialServer.
	Timeout time.Duration

	// Database is the default db name used when the Session.DB method
	// is called with an empty name, and is also used during the initial
	// authentication if Source is unset.
	Database string

	// ReplicaSetName, if specified, will prevent the obtained session from
	// communicating with any server which is not part of a replica set
	// with the given name. The default is to communicate with any server
	// specified or discovered via the servers contacted.
	ReplicaSetName string

	// Source is the db used to establish credentials and privileges
	// with a MongoDB server. Defaults to the value of Database, if that is
	// set, or "admin" otherwise.
	Source string

	// Service defines the service name to use when authenticating with the GSSAPI
	// mechanism. Defaults to "mongodb".
	Service string

	// ServiceHost defines which hostname to use when authenticating
	// with the GSSAPI mechanism. If not specified, defaults to the MongoDB
	// server's address.
	ServiceHost string

	// Mechanism defines the protocol for credential negotiation.
	// Defaults to "MONGODB-CR".
	Mechanism string

	// Username and Password inform the credentials for the initial authentication
	// done on the db defined by the Source field. See Session.Login.
	Username string
	Password string

	// PoolLimit defines the per-server socket pool limit. Defaults to
	// DefaultConnectionPoolLimit. See Session.SetPoolLimit for details.
	PoolLimit int

	// PoolTimeout defines max time to wait for a connection to become available
	// if the pool limit is reached. Defaults to zero, which means forever. See
	// Session.SetPoolTimeout for details
	PoolTimeout time.Duration

	// ReadTimeout defines the maximum duration to wait for a response to be
	// read from MongoDB.
	//
	// This effectively limits the maximum query execution time. If a MongoDB
	// query duration exceeds this timeout, the caller will receive a timeout,
	// however MongoDB will continue processing the query. This duration must be
	// large enough to allow MongoDB to execute the query, and the response be
	// received over the network connection.
	//
	// Only limits the network read - does not include unmarshalling /
	// processing of the response. Defaults to DialInfo.Timeout. If 0, no
	// timeout is set.
	ReadTimeout time.Duration

	// WriteTimeout defines the maximum duration of a write to MongoDB over the
	// network connection.
	//
	// This is can usually be low unless writing large documents, or over a high
	// latency link. Only limits network write time - does not include
	// marshalling/processing the request. Defaults to DialInfo.Timeout. If 0,
	// no timeout is set.
	WriteTimeout time.Duration

	// The identifier of the client application which ran the operation.
	AppName string

	// ReadPreference defines the manner in which servers are chosen. See
	// Session.SetMode and Session.SelectServers.
	ReadPreference *ReadPreference

	// Safe mostly defines write options, though there is RMode. See Session.SetSafe
	Safe Safe

	// FailFast will cause connection and query attempts to fail faster when
	// the server is unavailable, instead of retrying until the configured
	// timeout period. Note that an unavailable server may silently drop
	// packets instead of rejecting them, in which case it's impossible to
	// distinguish it from a slow server, so the timeout stays relevant.
	FailFast bool

	// Direct informs whether to establish connections only with the
	// specified seed servers, or to obtain information for the whole
	// cluster and establish connections with further servers too.
	Direct bool

	// MinPoolSize defines The minimum number of connections in the connection pool.
	// Defaults to 0.
	MinPoolSize int

	// The maximum number of milliseconds that a connection can remain idle in the pool
	// before being removed and closed.
	MaxIdleTimeMS int
	DialServer    func(addr *ServerAddr) (net.Conn, error)
}

DialInfo holds options for establishing a session with a MongoDB cluster. To use a URL, see the Dial function.

type GridFS

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

func (*GridFS) Close

func (g *GridFS) Close()

func (*GridFS) Create

func (g *GridFS) Create(name string) (file *GridFile, err error)

func (*GridFS) CreateStream

func (g *GridFS) CreateStream(name string) (*gridfs.UploadStream, error)

func (*GridFS) Find

func (g *GridFS) Find(query interface{}) *Query

func (*GridFS) Open

func (g *GridFS) Open(name string) (file *GridFile, err error)

func (*GridFS) OpenId

func (g *GridFS) OpenId(id bson.ObjectId) (file *GridFile, err error)

func (*GridFS) OpenStreamId

func (g *GridFS) OpenStreamId(id bson.ObjectId) (*gridfs.DownloadStream, error)

func (*GridFS) Remove

func (g *GridFS) Remove(name string) (err error)

func (*GridFS) RemoveId

func (g *GridFS) RemoveId(id interface{}) (err error)

type GridFile

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

func (*GridFile) Close

func (gf *GridFile) Close() (err error)

func (*GridFile) Id

func (gf *GridFile) Id() interface{}

func (*GridFile) Name

func (gf *GridFile) Name() string

func (*GridFile) Read

func (gf *GridFile) Read(p []byte) (n int, err error)

func (*GridFile) Size

func (gf *GridFile) Size() (bytes int64)

func (*GridFile) Write

func (gf *GridFile) Write(content []byte) (int, error)

type Index

type Index struct {
	Key    []string // Index key fields; prefix name with dash (-) for descending order
	Unique bool     // Prevent two documents from having the same index key

	//DropDups      bool     // deprecated since version 2.7.5 DropCollection documents with the same index key as a previously indexed one
	Background    bool   // Build index in background and return immediately
	Sparse        bool   // Only index documents containing the Key fields
	PartialFilter bson.M // Partial index filter expression

	// If ExpireAfter is defined the server will periodically delete
	// documents with indexed time.Time older than the provided delta.
	ExpireAfter time.Duration

	// Name holds the stored index name. On creation if this field is unset it is
	// computed by EnsureIndex based on the index key.
	Name string

	// Properties for spatial indexes.
	//
	// Min and Max were improperly typed as int when they should have been
	// floats.  To preserve backwards compatibility they are still typed as
	// int and the following two fields enable reading and writing the same
	// fields as float numbers. In mgo.v3, these fields will be dropped and
	// Min/Max will become floats.
	Minf, Maxf float64
	BucketSize float64
	Bits       int

	// Properties for text indexes.
	DefaultLanguage  string
	LanguageOverride string

	// Weights defines the significance of provided fields relative to other
	// fields in a text index. The score for a given word in a document is derived
	// from the weighted sum of the frequency for each of the indexed fields in
	// that document. The default field weight is 1.
	Weights map[string]int

	// Collation defines the collation to use for the index.
	Collation *Collation
}

func (*Index) ToIndexModels

func (i *Index) ToIndexModels() (model mongo.IndexModel, err error)

type Iter

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

func (*Iter) All

func (iter *Iter) All(result interface{}) error

func (*Iter) Close

func (iter *Iter) Close() error

func (*Iter) Done

func (iter *Iter) Done() bool

func (*Iter) Err

func (iter *Iter) Err() error

func (*Iter) Next

func (iter *Iter) Next(result interface{}) bool

type Mode

type Mode = readpref.Mode

type Pipe

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

func (*Pipe) All

func (p *Pipe) All(result interface{}) error

func (*Pipe) AllowDiskUse

func (p *Pipe) AllowDiskUse() *Pipe

func (*Pipe) Batch

func (p *Pipe) Batch(n int) *Pipe

func (*Pipe) Collation

func (p *Pipe) Collation(collation *Collation) *Pipe

func (*Pipe) Explain

func (p *Pipe) Explain(result interface{}) error

func (*Pipe) Iter

func (p *Pipe) Iter() *Iter

func (*Pipe) One

func (p *Pipe) One(result interface{}) (err error)

func (*Pipe) SetMaxTime

func (p *Pipe) SetMaxTime(d time.Duration) *Pipe

type Query

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

func (*Query) All

func (qr *Query) All(result interface{}) (err error)

func (*Query) AllowDiskUse

func (qr *Query) AllowDiskUse() *Query

func (*Query) Apply

func (qr *Query) Apply(change Change, result interface{}) (info *ChangeInfo, err error)

func (*Query) Batch

func (qr *Query) Batch(n int) *Query

func (*Query) Collation

func (qr *Query) Collation(collation *Collation) *Query

func (*Query) Comment

func (qr *Query) Comment(comment string) *Query

func (*Query) Count

func (qr *Query) Count() (int, error)

func (*Query) Distinct

func (qr *Query) Distinct(key string, result interface{}) (err error)

func (*Query) Explain

func (qr *Query) Explain(result interface{}) error

func (*Query) Hint

func (qr *Query) Hint(indexKey ...string) *Query

func (*Query) Iter

func (qr *Query) Iter() *Iter

func (*Query) Limit

func (qr *Query) Limit(n int) *Query

func (*Query) One

func (qr *Query) One(result interface{}) (err error)

func (*Query) Select

func (qr *Query) Select(selector interface{}) *Query

func (*Query) SetMaxTime

func (qr *Query) SetMaxTime(d time.Duration) *Query

func (*Query) Skip

func (qr *Query) Skip(n int) *Query

func (*Query) Sort

func (qr *Query) Sort(fields ...string) *Query

type QueryError

type QueryError struct {
	Code      int
	Message   string
	Assertion bool
}

QueryError is returned when a query fails

func (*QueryError) Error

func (err *QueryError) Error() string

type ReadPreference

type ReadPreference struct {
	// Mode determines the consistency of results. See Session.SetMode.
	Mode Mode

	// TagSets indicates which servers are allowed to be used. See Session.SelectServers.
	TagSets []bson.D
}

ReadPreference defines the manner in which servers are chosen.

type Safe

type ServerAddr

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

type Session

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

Session session session

func Dial

func Dial(url string) (*Session, error)

func DialWithInfo

func DialWithInfo(dialInfo *DialInfo) (session *Session, err error)

DialWithInfo establishes a new session to the cluster identified by info.

func New

func New(uri string) *Session

New session

Relevant documentation:

https://docs.mongodb.com/manual/reference/connection-string/

func NewFromMongoDriver

func NewFromMongoDriver(m *mongo.Client, database string) *Session

func (*Session) BuildInfo

func (s *Session) BuildInfo() (info BuildInfo, err error)

func (*Session) C

func (s *Session) C(collection string) *Collection

Collection returns coll

func (*Session) Close

func (s *Session) Close()

func (*Session) Connect

func (s *Session) Connect() error

Connect session client

func (*Session) Copy

func (s *Session) Copy() *Session

func (*Session) DB

func (s *Session) DB(db string) *Database

DB returns a value representing the named db.

func (*Session) DatabaseNames

func (s *Session) DatabaseNames() (names []string, err error)

func (*Session) Ping

func (s *Session) Ping() error

Ping verifies that the client can connect to the topology. If readPreference is nil then will use the client's default read preference.

func (*Session) Run

func (s *Session) Run(cmd interface{}, result interface{}) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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